When in doubt, test. However, faster for what?
If your end goal is to also display the pixels every frame, then line()
is probably going to be faster than pg.line(); image(pg)
because you will always have that extra copy operation that direct drawing doesn’t have – although you should test, as it might be a negligible difference depending on your image size.
If your goal is to, for example, render a billion circles as fast as possible in setup to create a static image, and you don’t care about screen updating and just want to know which is faster – one billion “line()” or “pg.line()” then just run some test loops with millis(). My guess (?) is that they are almost exactly the same – line() is actually a call to g.line(), so you are drawing to a PGraphics either way.
That’s what I’m seeing with a simple test sketch, anyway. Direct drawing of 100,000 randomly generated colored lines is the same speed using line(), g.line(), or pg.line().
/**
* DrawToPGraphicsTest
* 2019-08 Processing 3.4
* Compare drawing speeds to canvas, to PGraphics, to canvas-PGraphics.
* Example output:
* 30048 : 354 , 30402
* 29335 : 30405 , 59740
* 29729 : 59742 , 89471
*/
PGraphics pg;
int reps = 100000;
void setup(){
size(400,400);
pg = createGraphics(400,400);
}
void draw(){
if(frameCount==1) testCanvas(reps);
if(frameCount==2) testGraphics(g, reps);
if(frameCount==3) testGraphics(pg, reps);
if(frameCount==4) noLoop();
}
void testCanvas(int reps){
int startTime = millis();
for(int i=0; i<reps; i++){
stroke(random(255),random(255),random(255));
line(0,random(height),width,random(height));
line(random(width),0,random(width),height);
}
int endTime = millis();
println(endTime-startTime, ":", startTime, ",", endTime);
}
void testGraphics(PGraphics pg, int reps){
int startTime = millis();
pg.beginDraw();
for(int i=0; i<reps; i++){
pg.stroke(random(255),random(255),random(255));
pg.line(0,random(height),width,random(height));
pg.line(random(width),0,random(width),height);
}
pg.endDraw();
int endTime = millis();
println(endTime-startTime, ":", startTime, ",", endTime);
}