4 ms·
What's the Fastest Way to Code a Loop in Javascript?
- code_duck 16y agoSo, anyone have results for browsers that were released within the past 2 years?
- donohoe 16y agoWhat 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 16y agoIt 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 16y agoOn 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 16y agoIsn't LOOP one of those microcoded instructions that actually runs slower on modern processors than a RISC-style separate decrement and compare?
- derefr 16y agoIt'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 16y agoSome 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.
- Sharlin 16y agoGiven 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 16y agoWould be interesting to see some benchmarks against modern browsers, I don't have the bandwidth at the moment though.
- elimisteve 16y agoUsing emacs :-)
- hackermom 16y agoI 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".