Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do new browsers optimize for loops differently?

I was reading Nicholas Zackas' High Performance Javascript in which he discusses optimizing a for loop by reversing it and minimizing its property lookups.

Instead of:

for (var i = 0; i < items.length; i++ ) {
  processItems(items[i]);
}

You get:

for (var i = items.length; i--; ) {
  processItems(items[i]);
}

At the time of writing, the execution times were "up to 50%-60% faster than the original." Yet I created a jsperf and in Firefox and Chrome I've noticed that the optimized for loop is actually noticeably slower, especially in Firefox.

enter image description here

Do newer browsers optimize for loops differently? Is the most efficient way to write a for loop now simply the basic way?

like image 792
stinkycheeseman Avatar asked Mar 15 '13 17:03

stinkycheeseman


1 Answers

Perhaps you could include the test-case, as well, rather than forcing the browser to cast the answer to boolean?

var i, arr = [...];
for (i = arr.length; i > 0; i -= 1) { arr[i-1] = 1; }

First, your loop is casting the 0 as an end-condition, second, arr[i] where i = arr.length is undefined, which means that Chrome will de-optimize the loop in regard to accessing that array, due to implicit types, under the hood of Chrome.

So now, as far as Chrome is concerned, you've got two large de-optimizations happening in Zakas' use-case.

JavaScript engines have indeed progressed a very long way in the past 3 years, in regard to how they optimize things behind the scenes. Now, it's less about writing code to trick the engine into optimizing better (which can now be counter-intuitive to the actual optimization-intelligence being built into modern browsers' JS compilers), and more about writing optimized code in the regular sense -- knowing which data-types to use, when, et cetera.

I think that you're going to find that if you try the test again, changing those two things that I recommend in the code-sample above, that while the numbers might not match exactly, they're going to be a lot closer to the forward performance.

like image 184
Norguard Avatar answered Oct 04 '22 11:10

Norguard