getImageData pixel by pixel or all image (v2)

Revision 2 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 = 100;
canvas.width = 100;
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
for( var x = 0; x < canvas.width; x++ ) {
    for( var y = 0; y < canvas.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 cpa = ctx.getImageData( 0, 0, 20, 20 ).data;
for( var x = 0; x < canvas.width; x++ ) {
    for( var y = 0; y < canvas.height; y++ ) {
        if ( cpa[ ( x * 80 ) + ( y * 4 ) + 4 ] > 128 ) {
            coords[ coords.length ] = [x,y];  
        } 
    }  
}
ready
entire thing one loop
var cpa = ctx.getImageData( 0, 0, 20, 20 ).data,
    all = canvas.width * canvas.height,
    x = canvas.width;
for ( var i = 0; i < all; i++ ) {
    if ( cpa[ (i*4) + 4 ] > 128 ) {
            coords[ coords.length ] = [ Math.floor( i/x), i % x ];  
    }  
}
ready

Revisions

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