

What's the Fastest Way to Code a Loop in Javascript? - rbxbx
http://blogs.sun.com/greimer/entry/best_way_to_code_a

======
Sharlin
Given the amount of work that has gone into optimizing Javascript speed in
browsers during the past two years, I'd say these results are completely
obsolete.

~~~
rbxbx
Would be interesting to see some benchmarks against modern browsers, I don't
have the bandwidth at the moment though.

------
code_duck
So, anyone have results for browsers that were released within the past 2
years?

~~~
d0mine
<http://blogs.sun.com/greimer/resource/loop-test.html>

~~~
code_duck
Exceeds my wildest hopes and dreams. Thank you.

------
donohoe
What surprises me is are some of the results like this:

    
    
      IE 7.0.5730.11 / WinXP SP2
      Native Array (length=1000, looped 100 times)
    

While loop in reverse, simplifying the test condition.

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

Took _0ms_ to execute... very unexpected

~~~
austintaylor
It makes sense that a zero comparison is faster, but 0ms does seem strange.
It's 31ms for a basic for loop on the same platform, whereas in Safari the
times are 2ms and 5ms respectively, which seems a lot more reasonable.

Is it possible that IE 7 is deleting the whole loop as a no-op?

~~~
derefr
On IA-32, a decrementing-until-zero loop gets its own instruction
(called—unsurprisingly—LOOP.) If it optimized in that one case, it would take
_microseconds_ to execute the whole test, which would show up as 0ms.

~~~
prodigal_erik
Isn't LOOP one of those microcoded instructions that actually runs slower on
modern processors than a RISC-style separate decrement and compare?

~~~
derefr
It's a slow instruction, but it's a _single_ instruction—in a loop with an
empty body, this creates the best possible situation for memory locality: you
just keep reading the same memory address/cache line over and over.

------
jallmann
Some very interesting results -- I didn't expect the while loop in reverse to
be so fast, and this is consistent across browsers.

The presentation needs work, though. Would some charts be so difficult to
make? Much easier to compare results that way.

edit: note this post is from 2008.

~~~
teamonkey
I'd also like to see the same results after the code had been compiled with
something like Google Closure.

~~~
apgwoz
well, i'd _hope_ that in most cases closure would compile to var i =
arr.length, since the body of the loop was nil.

------
hackermom
I personally always (when applicable, of course) go with a reversed while-
loop, because of its neat and tidy nature, and being "easy on the eye".

------
elimisteve
Using emacs :-)

