canvas pixel loop

JavaScript performance comparison

Test case created by Ilmari Heikkinen

Preparation code

<script>
  var canvas = document.createElement('canvas');
  canvas.width = 256;
  canvas.height = 256;
  var ctx = canvas.getContext('2d');
  ctx.fillRect(0, 0, 256, 256);
  var id = ctx.getImageData(0, 0, 256, 256);
  var pixels = id.data;
  var length = pixels.length;
  var width = id.width;
  var height = id.height;
</script>
    

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
property accesses 2d
for (var y = 0; y < id.height; y++) {
 for (var x = 0; x < id.width; x++) {
  var off = (y * id.width + x) * 4;
  id.data[off] += 10;
  id.data[off + 1] += 20;
  id.data[off + 2] += 30;
  id.data[off + 3] += 40;
 }
}
pending…
property accesses 1d
for (var i = 0; i < id.data.length; i += 4) {
 id.data[i] += 10;
 id.data[i + 1] += 20;
 id.data[i + 2] += 30;
 id.data[i + 3] += 40;
}
pending…
local variables 2d
for (var y = 0; y < height; y++) {
 for (var x = 0; x < width; x++) {
  var off = (y * width + x) * 4;
  pixels[off] += 10;
  pixels[off + 1] += 20;
  pixels[off + 2] += 30;
  pixels[off + 3] += 40;
 }
}
pending…
local variables 1d
for (var i = 0; i < length; i += 4) {
 pixels[i] += 10;
 pixels[i + 1] += 20;
 pixels[i + 2] += 30;
 pixels[i + 3] += 40;
}
pending…
local variables 1d hack one
for (var i = -1; i < length;) {
 pixels[++i] += 10;
 pixels[++i] += 20;
 pixels[++i] += 30;
 pixels[++i] += 40;
}
pending…
local variables 1d hack two
var i = -1;
while (i < length) {
 pixels[++i] += 10;
 pixels[++i] += 20;
 pixels[++i] += 30;
 pixels[++i] += 40;
}
pending…
local variables 1d hack three
var i = length;
while (i >= 0) {
 pixels[--i] += 40;
 pixels[--i] += 30;
 pixels[--i] += 20;
 pixels[--i] += 10;
}
pending…
local variables 2d cache-unfriendly
for (var x = 0; x < width; x++) {
 for (var y = 0; y < height; y++) {
  var off = (y * width + x) * 4;
  pixels[off] += 10;
  pixels[off + 1] += 20;
  pixels[off + 2] += 30;
  pixels[off + 3] += 40;
 }
}
pending…
local variables 1d hack four
for (var i = 0; i < length;) {
 pixels[i++] += 10;
 pixels[i++] += 20;
 pixels[i++] += 30;
 pixels[i++] += 40;
}
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

0 Comments