On Mar 10, 2:06 am, Stamen Georgiev <[email protected]> wrote:
> Just wrote a small test at jsperf for testing a for loop to iterate an
> array of objects:http://jsperf.com/if-with-i

If loops are written using simple conditions and logic there is little
be gained from optimisation as the loop itself is usually an
insignigicant portion of the execution time of a program. When testing
for speed, you will get different results in different browsers (as
you've discovered) and even versions of the same browser. What is
fastest in one may not be in another.

In most modern browsers, there is very little speed difference between
for, while and do loops. For example, comparing IE 6 and Firefox 3.6,
there is no significant difference between:

  while (i--) {a = b[i];}

  while (a = b[--i]) {}

  for (i = b.length; i;) {a = b[--i];}

  do { a = b[--i]; } while(i)

  do {} while(a = b[--i])

Note that to get meaningful results, the above loops must run at least
500,000 iterations (about 120ms for IE and 16ms for Firefox on my PC),
which should give you a hint about how little is to be gained by small
optimisations of the loop.

Putting an assignment in the condition may be a tad faster in some
cases but can also be slower and make for less readable code. It can
also introduce hard to find bugs, for example, there is an old version
of Opera that given:

  while (a = b[--i])

would helpfully change it to:

  while (a == b[--i])

so it was necessary to write:

  while ((a = b[--i]))

Some have adopted that as a convention to indicate that they really do
want assignment and not comparison.

There is also a perception that less code is faster, but that is often
wrong. A larger number of simple operations is often faster than a
smaller number of complex operations, probablly because complilers are
optimised to handle common cases so when adding complexity, the
compiler optimistation is bypassed.

So in the above case it is clearer and sometimes faster (rarely
slower) to write:

  while (--i) {
    a = b[i];
  }

Just write clear, easily read and maintained code and *if* you have a
performance issue, deal with it then. You will likely find far more
rewarding optimisations elsewhere (especially if you are modifying a
DOM).


--
Rob

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to