Is it worth caching the length of an array in a Javascript loop?

JavaScript performance comparison

Revision 84 of this test case created by victmo

Info

Prefix and postfix operators benchmarking (large array)

http://stackoverflow.com/questions/5349425/whats-the-fastest-way-to-loop-through-an-array-in-javascript

Preparation code

<script>
  var myArray = [];
  for(var i=0; i<500; i++) myArray[i]=i;

  var res = 0;
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
for, cached, <, post
for(var i=0, len=myArray.length; i<len; i++){
  res += myArray[i];
}
window.res = res;
pending…
for, cached, !=, post
for(var i=0, len=myArray.length; i!=len; i++){
  res += myArray[i];
}
window.res = res;
pending…
for, cached, <, pre
for(var i=0, len=myArray.length; i<len; ++i){
  res += myArray[i];
}
window.res = res;
pending…
for, cache, !=, pre
for(var i=0, len=myArray.length; i!=len; ++i){
  res += myArray[i];
}
window.res = res;
pending…
for, uncached, <, post
for(var i=0; i<myArray.length; i++){
  res += myArray[i];
}
window.res = res;
pending…
for, uncached, !=, post
for(var i=0; i!=myArray.length; i++){
  res += myArray[i];
}
window.res = res;
pending…
for, uncached, <, pre
for(var i=0; i<myArray.length; ++i){
  res += myArray[i];
}
window.res = res;
pending…
for, uncached, !=, pre
for(var i=0; i!=myArray.length; ++i){
  res += myArray[i];
}
window.res = res;
pending…
while, post, desc
var len = myArray.length;
while (len--) {
  res += myArray[len];
}
window.res = res;
pending…
while, post, asc
var len=myArray.length, ilen=len;
while (len--) {
  res += myArray[ilen - len];
}
window.res = res;
pending…
while, pre, desc
var len = myArray.length;
while (--len) {
  res += myArray[len];
}
window.res = res;
pending…
while, pre, asc
var len=myArray.length, ilen=len;
while (--len) {
  res += myArray[ilen - len];
}
window.res = res;
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment