Pixels array p5.js vs java improving speed

I have made the following changes

  1. calculate the k array in setup rather than every frame
  2. using the array.length rather than calculate the number of pixels in every loop iteration.
  3. the k array does not use the alpha channel so set alpha to 255 (opaque) directly
  4. get the rgb channel values directly from the pixel color rather that via the graphics objectt

The last one should avoid p5.js doing a lot of internal color mode calcs, although I am not sure.

let a = [];
let k = [];
let u, v, r = 42, g = 84, b = 128, p = 0, s = 32;

function setup() {
  createCanvas((w = 300), w);
  pixelDensity(1);
  for (let x = 0; x < w; x ++) {
    for (let y = 0; y < 4 * w; y ++) {
      a[x * 4 + y  * 4* w] = int((b + b * sin(x / 32.0) +
        (b + b * cos(y / s)) +
        (b + b * sin(sqrt(x * x + y * y) / s))) / 4);
    }
  }
  for (i = 0; i < 128; i++) {
    u = sin(i * 0.12);
    v = sin(i * PI / 50 + 0.79);
    k[i] = color(r + u * b, g + v * b, b + u * b);
  }
}

function draw() {
  p++;
  loadPixels();
  for (let i = 0; i < pixels.length; i += 4) {
    c = k[(a[i] + p) & 127];
    pixels[i] = c._getRed();
    pixels[i + 1] = c._getGreen();
    pixels[i + 2] = c._getBlue();
    pixels[i + 3] = 255;
  }
  updatePixels();
}

You would need to do some bench marking to see if any improvement is significant :smile:

2 Likes