array.length vs array[0] for checking array contents (v2)

Revision 2 of this benchmark created by Premasagar Rose on


Description

Test the fastest method of checking the existence of remaining content when shifting items from an array.

After seeing the following code in jQuery's Deferred implementation.

try {
  while( callbacks[ 0 ] ) {
    callbacks.shift().apply( context, args );
  }
}
finally {
  fired = [ context, args ];
  firing = 0;
}

Source: https://github.com/jquery/jquery/blob/1.6.1/src/deferred.js#L58

Preparation HTML

<script>
  // Create an array with 10,000 items.
  var array = [], undefined;
  for (var i = 0, t = 10000; i < t; i++) {
     array[i] = true;
  }
  
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
array.length
while (array.length) {
  array.shift();
}
 
ready
array[0] !== undefined
while (array[0] !== undefined) {
  array.shift();
}
 
ready
array[0]
// Assumes all array contents is truthy, eg. a function. 
while (array[0]) {
  array.shift();
}
ready
Cache length
var len = array.length;

while (len--) {
  array.shift();
}
ready

Revisions

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