getImageData pixel by pixel or all image (v4)

Revision 4 of this benchmark created on


Description

Which is faster? A bunch of getImageData calls or one big one with the RAM munchies?

Preparation HTML

<script>
var canvas = document.createElement( 'canvas' );
canvas.height = 20;
canvas.width = 20;
var ctx = canvas.getContext( '2d' ),
    coords = [];


ctx.beginPath();
ctx.strokeStyle = "#999";
ctx.lineWidth = 5;
ctx.moveTo( 5,5);
ctx.lineTo( 915, 915 );
ctx.stroke();
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
pixel by pixel
// find drawn pixels pixel by pixel
var width = canvas.width,
height = canvas.height;
for( var x = 0; x < width; x++ ) {
    for( var y = 0; y < height; y++ ) {
        var data = ctx.getImageData( x, y, 1, 1 ).data;
        // if there's alpha, there's a pixel yo
        if ( data[3] > 128 ) {
            coords[ coords.length ] = [x,y];  
        } 
    }  
}
ready
entire thing
// do it for a whole data obj
var width = canvas.width,
height = canvas.height,
cpa = ctx.getImageData(0, 0, width, height).data;

for( var x = 0; x < width; x++ ) {
    for( var y = 0; y < height; y++ ) {
        if ( cpa[ ( x * width ) + ( y * 4 ) + 3 ] > 128 ) {
            coords[ coords.length ] = [x,y];  
        } 
    }  
}
ready
entire thing one loop
var width = canvas.width,
height = canvas.height,
cpa = ctx.getImageData( 0, 0, width, height ).data,
    all = canvas.width * canvas.height;
for ( var i = 0; i < all; i++ ) {
    if ( cpa[ (i*4) + 3 ] > 128 ) {
            coords[ coords.length ] = [ (i/width) << 0, i % width ];  
    }  
}
ready

Revisions

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