putImageData vs JS PNG

JavaScript performance comparison

Test case created by OSM Buildings

Preparation code

<canvas></canvas>
<script src="http://www.xarg.org/download/pnglib.js"></script>
<script>
var width = 400, height = 300;
var canvas = document.getElementsByTagName('canvas')[0];
var context = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
context.fillStyle = '#ffcc00';

var rand = function(min, max) {
  var r;
  do {
    r = Math.random();
  } while (r === 1.0);
  return min + parseInt(r * (max - min + 1), 10);
};

var data = [];
for (var i = 0; i < width * height; i++) {
  data[i] = {
    r: rand(0, 255),
    g: rand(0, 255),
    b: rand(0, 255),
    a: rand(0, 255)
  };
}
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
putImageData
var imgData = context.getImageData(0, 0, width, height),
        pixels = imgData.data;

var k, p;
for (var i = 0, il = data.length; i < il; i++) {
  k = i*4;
  p = data[i];
        pixels[k]   = p.r;
        pixels[k+1] = p.g;
        pixels[k+2] = p.b;
        pixels[k+3] = p.a;
}

context.putImageData(imgData, 0, 0);
var res = canvas.toDataURL();
pending…
JS PNG
var png = new PNGlib(width, height);
var k, p;
for (var i = 0, il = data.length; i < il; i++) {
  k = i*2;
  p = data[i];
  png.buffer[png.index(k, k+1)] = png.color(p.r, p.g, p.b, p.a);
}

//var res = 'data:image/png;base64,' + png.getBase64();
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. Here’s a list of current revisions for this page:

0 comments

Add a comment