Skip to content

Instantly share code, notes, and snippets.

@bgadrian
Created March 16, 2015 16:57
Show Gist options
  • Save bgadrian/c676893b312dbc8cf6b8 to your computer and use it in GitHub Desktop.
Save bgadrian/c676893b312dbc8cf6b8 to your computer and use it in GitHub Desktop.
Alternative iteration loops for large arrays
//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