Skip to main content

Bug Tracker

Side navigation

#5496 closed enhancement (wontfix)

Opened November 12, 2009 01:27PM UTC

Closed November 12, 2009 02:17PM UTC

Last modified November 26, 2009 02:10AM UTC

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--) {

// arr[i]


Thanks: DBJ

Attachments (0)
Change History (3)

Changed November 12, 2009 01:28PM UTC by dbjdbj comment:1

Ce we please ---> Can we please

Changed November 12, 2009 02:17PM UTC by john comment:2

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.

Changed November 26, 2009 02:10AM UTC by dbjdbj comment:3

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