Bug Tracker

Opened 13 years ago

Closed 13 years ago

Last modified 13 years ago

#5496 closed enhancement (wontfix)

for() loops optimization

Reported by: dbjdbj Owned by:
Priority: major Milestone: 1.4
Component: core Version: 1.3.2
Keywords: optimization Cc:
Blocked by: Blocking:


Obvious this is , but still has to be done ;o)

Ce we please optimise the "most common form" of for() loops? Namely the ones iterating over an array or "array like" objects.

for (var i = fromIndex; i < arr.length; i++) {

This for loop looks up the .length property of the array (arr) each time through the loop. Simply by setting a variable to store this number at the start of the loop, you can make the loop run much faster:

for (var i = fromIndex, ii = arr.length; i < ii; i++) {

This loop is better in that it avoids a property lookup each time through the loop, but this particular for loop is so simple that it could be further simplified into a while loop, which will run much faster again:

var i = arr.length; while (i--) {



Thanks: DBJ

Change History (3)

comment:1 Changed 13 years ago by dbjdbj

Ce we please ---> Can we please

comment:2 Changed 13 years ago by john

Component: unfilledcore
Milestone: 1.4
Resolution: wontfix
Status: newclosed

However this particular change sacrifices clarity and legibility for a near imperceptible amount of performance. I would need to see some serious numbers before landing something like this. The leap from not caching the length to caching it is much larger than going from a for loop to a while.

comment:3 Changed 13 years ago by dbjdbj

True. But. I have done speed cheks and comparisons for different each() methods. What I have found is that different browsers show different fluctuations and speed-ups. This is not surprising since they have (much) different JS engines, I guess ... Something like test swarm , I think, would yield interesting data when compared between the browsers.

3D graphs anyone ;o) ?

x = iterable object size, y = time, z = browser

Note: See TracTickets for help on using tickets.