Skip to content

Instantly share code, notes, and snippets.

@eliperelman
Created July 6, 2011 03:33
Show Gist options
  • Save eliperelman/1066503 to your computer and use it in GitHub Desktop.
Save eliperelman/1066503 to your computer and use it in GitHub Desktop.
Speedy Loops
var arr = ['apple', 'banana', 'cheese', 'donut', 'egg', 'fish'];
var send = function (item) {
$.ajax({
type: 'post',
dataType: 'json',
url: '/Foods/Consume',
data: { food: item }
});
};
// Normal for loop:
for (var i = 0, len = arr.length; i < len; i++) {
send(arr[i]);
}
// Faster reverse while loop:
var i = arr.length;
while (i--) {
send(arr[i]);
}
@atk
Copy link

atk commented Jul 6, 2011

while is not required, you can use:

for (var i = arr.length; i--; ) {
  send(arr[i]);
}

If you plan on using the iterated instance multiple times, you can make this even faster by only once initializing the variant:

for (var i = arr.length, item; item = arr[i--], i; ) {
  // do a lot more stuff with item
  send(item);
}

If there are only truthish elements in your loop, you can even save 2 bytes:

for (var i = arr.length, item; item = arr[i--]; ) {
  // do a lot more stuff with item
  send(item);
}

@eliperelman
Copy link
Author

Understood, but the purpose of this post is to note that the reverse while is the fastest performing JS loop: http://blogs.oracle.com/greimer/entry/best_way_to_code_a

@atk
Copy link

atk commented Jul 7, 2011

I would guess the for loop in reverse being slower than the while loop in reverse is due to the testing conditions, which are rather unprecise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment