Extremely Slow Javascript Loop

This is, in a way, a continuation of my previous question .

I created jsPerf that compares several ways to take a 1-dimensional array of RGB values

var rgb = [R, G, B, R, G, B...] 

And convert them to RGBA values ​​for HTML5 canvas (where the alpha channel is always 255, completely opaque).

 var rgba = [R, G, B, 255, R, G, B, 255...] 

In my tests, I found that one of the loops I tested called "For Loop" was astronomically slower than the other loops. When other cycles completed the operation hundreds of millions of times per second , it weighed a whopping 86 times per second . The loop can be found in the jsPerf link above, but here is some code with "For Loop" and "4 * unrolled, skip alpha", one of the faster loops in the test.

 //Setup for each test function newFilledArray(length, val) { var array = Array(length); for (var i = 0; i < length; i++) { array[i] = val; } return array; } var w = 160; //width var h = 144; //height var n = 4 * w * h; //number of length of RGBA arrays var s = 0, d = 0; //s is the source array index, d is the destination array index var rgba_filled = newFilledArray(w*h*4, 255); //an RGBA array to be written to a canvas, prefilled with 255 (so writing to the alpha channel can be skipped var rgb = newFilledArray(w*h*3, 128); //our source RGB array (from an emulator internal framebuffer) //4*unrolled, skip alpha - loop completes (exits) 185,693,068 times per second while (d < n) { rgba_filled[d++] = rgb[s++]; rgba_filled[d++] = rgb[s++]; rgba_filled[d++] = rgb[s++]; d++; } //For Loop - loop completes (exits) 85.87 times per second for (var d = 0; d < n; ++d) { rgba_filled[d++] = rgb[s++]; rgba_filled[d++] = rgb[s++]; rgba_filled[d++] = rgb[s++]; } 

How can it be so incredibly similar in syntax, but so far removed in terms of performance?

+7
performance javascript loops
source share
1 answer

The reason the for loop is so slow is because it is the only valid test case; all other test cases never reset, among others, the value d , so the first iteration is normal, and the rest is obviously super fast :)

This jsperf gives the best result, so the for-loop is only slightly slower than the fastest result.

Update

As bfavaretto, you should also specify reset s and the target array that you create to get a more consistent result. Its results can be found here .

+10
source share

All Articles