2

According to What's the Fastest Way to Code a Loop in JavaScript? and Why is to decrement the iterator toward 0 faster than incrementing , a basic for loop is slower than a for - loop with simplified test condition, i.e.:

console.log("+++++++");
var until = 100000000;

function func1() {
  console.time("basic")
  var until2 = until;
  for (var i = 0; i < until2; i++) {}
  console.timeEnd("basic")
}

function func2() {
  console.time("reverse")
  var until2 = until;
  for (until2; until2--;) {}
  //while(until2--){}
  console.timeEnd("reverse")
}

func1();
func2();

As you might see the first function is, contrary to expectations, faster than the second. Did something change since the release of this oracle article, or did I do something wrong?

Community
  • 1
  • 1
InsOp
  • 2,425
  • 3
  • 27
  • 42
  • Running your code multiple times in Chrome's console, sometimes the basic loop is faster, sometimes the reverse loop is faster. – nnnnnn Jun 12 '15 at 11:39

1 Answers1

4

Yes, something has changed since the article was released. Firefox has gone from version 3 to version 38 for one thing. Mostly when a new version of a browser is released, the performance of several things has changed.

If you try that code in different versions of different browsers on different systems, you will see that you will get quite a difference in performance. Different browsers are optimised for different Javascript code.

As performance differs, and you can't rely on any measurements to be useful for very long, there are basically two principles that you can follow if you need to optimise Javascript:

  • Use the simplest and most common code for each task; that is the code that browser vendors will try to optimise the most.

  • Don't look for the best performance in a specific browser, look for the worst performance in any brower. Test the code in different browsers, and pick a method that doesn't give remarkably bad performance in any of them.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005