shift() vs pop() vs for vs while

Benchmark created by Gilmore Davidson on


Description

Best way of running through an array of values and clearing the array (e.g. a callback queue)

Preparation HTML

<script>
 var arr1 = [],
     arr2, arr3, arr4;
 for (var i = 0; i < 1000; i++) {
  arr1.push(i);
 }
 arr2 = arr1.slice();
 arr3 = arr1.slice();
 arr4 = arr1.slice();
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
shift
var value;
while (value = arr1.shift()); // Preserves order
ready
pop
var value;
while (value = arr2.pop()); // Reverse order
ready
for
var value;
for (var i = 0, l = arr3.length; i < l; i++) value = arr3[i];
arr3 = []; // Manual reset
ready
while
var value, i = arr4.length;
while (i--) value = arr4[i];
arr4 = []; // Manual reset
ready

Revisions

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

  • Revision 1: published by Gilmore Davidson on