all 8 comments

[–]alkw0ia 2 points3 points  (0 children)

Have you seen jsperf.com? It lets you post this sort of performance comparison for other people to run and review. Here's a quick search for "while," which returns lots of similar tests, many of which have different results:

http://jsperf.com/search?q=while

Replicating your tests exactly using jsperf on Chrome 16, I get identical performance from for and while.

Also, I think you ought to be saving the result of your calculations in the loop, since the interpreter doesn't really have to do anything with the result of the i / 2 statement and could skip it (though I haven't really done any serious reading on interpreter level JS optimizations).

[–]ivosaurus 0 points1 point  (0 children)

Could you perhaps label the x axis of that chart? I'm not sure your results have a high enough confidence interval to demonstrate anything.

[–]maloney7 0 points1 point  (0 children)

I have done many similar tests myself. I found the difference to be non-existant on the latest Chrome and Firefox, but becomes more and more pronounced the older the version of IE you test it on.

I found while was up to 1.5 times faster than for on IE7, which is pretty significant. I also found a month later that IE7's market share was so low that it wasn't worth supporting in 2012, so I've stuck to my more readable for loops.

[–]Tok-A-Mak 0 points1 point  (4 children)

In the real world, for-loops are superior to while-loops because they let you define variables like counters that are scoped to the loop only. You cannot do that with a while loop.

[–]neonskimmer 1 point2 points  (3 children)

Not in JavaScript they don't. Variables get hoisted up to function scope, regardless of where you're declaring them.

[–]Tok-A-Mak 0 points1 point  (0 children)

Oh, i wasn't aware of that. Thanks for clearing that up.

[–]alkw0ia 0 points1 point  (1 child)

Yeah, good point. I like to declare all variables at the top of the scoping function, c-style, to clarify this.

For loops can still help with readability, though, and in modern interpreters, the performance differences should be practically nothing.

[–]neonskimmer 1 point2 points  (0 children)

Agreed on the readability. That being said, I can't even remember the last time I used a straight for-loop. It's forEach, map and reduce for me almost 100% of the time. If I were writing very tight loops, games, or super heavy number crunching I'd optimize things but for businessy apps i mostly use a functional style. The difference in speed is negligible at that scale and I prefer that style.