Variable array vs array method

JavaScript performance comparison

Test case created by Rich

Preparation code

<script>
  var array1 = new Array();
  for (var i = 0; i < 1000000; i++) {
   array1[i] = i;
  }
  var array2 = new Array();
  for (var i = 0; i < 1000000; i++) {
   array2[i] = i;
  }
  var array1a = new Array();
  var array2a = new Array();
  
  function getArray1() {
   return array1;
  }
  
  function getArray2() {
   return array2;
  }
</script>
    

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Reference the method.
for (var x = 0, len = getArray1().length; x < len; x++) {
 array1a[x] = getArray1()[x];
}
pending…
Reference variable
var array2Values = getArray2();
for (var x = 0, len = array2Values.length; x < len; x++) {
 array2a[x] = array2Values[x];
}
pending…

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

Compare results of other browsers

1 Comment

Rich (revision owner) commented :

Turns out on Firefox, these are very similar - but on IE or Chrome, the variable reference is faster consistently.