Created
March 16, 2015 16:57
-
-
Save bgadrian/c676893b312dbc8cf6b8 to your computer and use it in GitHub Desktop.
Alternative iteration loops for large arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//The book Speed Up Your Site (New Riders) introduced a version of Duff’s Device in JavaScript that moves the processing of the extra array items outside the main loop, allowing the switch statement to be removed and resulting in an even faster way of processing a large number of items: | |
var iterations = Math.floor(values.length / 8); | |
var leftover = values.length % 8; | |
var i = 0; | |
if (leftover > 0){ | |
do { | |
process(values[i++]); | |
} while (--leftover > 0); | |
} | |
do { | |
process(values[i++]); | |
process(values[i++]); | |
process(values[i++]); | |
process(values[i++]); | |
process(values[i++]); | |
process(values[i++]); | |
process(values[i++]); | |
process(values[i++]); | |
} while (--iterations > 0); | |
//Duff’s Device, and the modified version presented here, is useful primarily with large arrays. For small arrays, the performance gain is minimal compared to standard loops. Therefore, you should attempt to use Duff’s Device only if you notice a performance bottleneck relating to a loop that must process a large number of items. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment