Processing Performance Test 2

The second performance test is to compare the performance among three ways to copy from one PImage to another with exactly the same size. The first method uses the PImage.copy function. The second method use the arrayCopy function to copy directly from one pixels array to another. The third method uses a linear loop to traverse the pixels array one by one.
 

/*
  Comparing the use of PImage.copy, arrayCopy and explicit for loop to copy one PImage
 to another.
 */
PImage img1, img2;
 
void setup() {
  size(displayWidth, displayHeight);
  img1 = loadImage("bigSample.jpg");
  img2 = createImage(img1.width, img1.height, ARGB);
  img1.loadPixels();
  img2.loadPixels();
}
 
void draw() {
  background(0, 0, 0);
 
  long n = System.nanoTime();
  img2.copy(img1, 0, 0, img1.width, img1.height, 0, 0, img2.width, img2.height);
  img2.updatePixels();
  long elapsedTime = (System.nanoTime() - n)/1000;
  println("PImage.copy: " + elapsedTime);
  image(img2, 0, 0);
 
  n = System.nanoTime();
  arrayCopy(img1.pixels, img2.pixels);
  img2.updatePixels();
  elapsedTime = (System.nanoTime() - n)/1000;
  println("arrayCopy: " + elapsedTime);
  image(img2, 0, 0);
 
  int cnt = img1.width*img1.height;
  n = System.nanoTime();
  for (int i=0; i<cnt; i++) {
    img2.pixels[i] = img1.pixels[i];
  }
  img2.updatePixels();
  elapsedTime = (System.nanoTime() - n)/1000;
  println("For loop copy: " + elapsedTime);
  image(img2, 0, 0);
  noLoop();
}

The results listed here are the average of five runs.

  • PImage.copy: 44,744
  • arrayCopy: 1,238
  • For loop copy: 7,885

It is pretty obvious the arrayCopy method is the fastest one.