Should I trust modern browsers to optimize code for me?
Are there JS compilers that do not optimize this loop?
for (var i = fromIndex; i < arr.length; i++) { ...}
In this criticism against Google Closure, it is said that a better loop would be
for (var i = fromIndex, ii = arr.length; i < ii; i++) {
In every other language I've known, I trust the compiler to do these things for me. I suspect that Google Chrome and modern browsers do these kinds of optimizati开发者_如何学运维ons ... am I wrong?
There are more examples in that article, like long switch cases which suppodely perform poorly. Is this still the case nowadays with Chrome and FF 4.0 (I hear good things about IE 9 as well)?
The above examples are NOT the same. If you do the former then arr.length
will be checked every loop iteration and will inherently perform more poorly. The reason for this is let's say you had the following loop:
for (var i = 0; i < arr.length; i++) {
arr.splice(i,1);
}
In this case arr.length
can't be cached because it will decrease in size every loop iteration. For most cases however your array will remain the same length throughout the loop and so you should cache the length as in your latter example so as to prevent the extra chain look-up.
Most browser should optimize for this sort of stuff but there is no guarantee. Regardless you really shouldn't be worrying about this level of optimization unless your doing a heck of a lot of looping.
No. It's an interpreter not a compiler.
JavaScript is dynamic you can't make anywhere near as many optimisations as you would with a static language.
The fact you have type freedom in JavaScript and having eval means that most optimisations a normal (C++) compiler would make on similar procedural code are not safe to make.
Also the aim of the interpreter is to interpret your code as fast as possible and the run it as fast as possible.
The aim of a compiler is to make your code as fast as possible.
On a separate note, Chrome, FF4(5) and IE9(10) are fast. You don't need to make micro optimisations like this. Although if you do have bottlenecks you still need to optimise simple things by hand (including loop unrolling)
精彩评论