Skip to content

Comment on Google Closure: How not to write JavaScript

Comments

Example 1: Slow Loop

The author claims writing:

  for (var i = fromIndex; i < arr.length; i++) {
…is slow and can be much faster as…
  for (var i = fromIndex, ii = arr.length; i < ii; i++) {
Speed aside, this introduces a bug if the length of the array changes in the body of the loop, but ignoring this booby trap I ran benchmarks on the original clear version and the slightly more complicated fragile version.
                        clear     fragile
  empty loop body         5ms         1ms
  single number add       7ms         6ms
  single DOM lookup      82ms        81ms
That is for an array of a million elements on an iMac running Safari. (Apparently Safari is particularly good at doing nothing, but otherwise this "optimization" is lost in the loop body's time.)

Edit: I checked Chrome on Linux as well. It was also unimpressive.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.