views:

96

answers:

4

I have been writing a JS algorithm. Its blazing fast in chrome and dog slow in FF. In the chrome profiler, I spend <10% in a method, in FF the same method is 30% of the execution time. Are there javascript constructs to avoid because they are really slow in one browser or another?

One thing I have noticed is that things like simple variable declaration can be expensive if you do it enough. I sped up my algorithm noticable by not doing things like

var x = y.x;
dosomthing(x);

and just doing

dosomething(y.x)

for example.

+5  A: 
T.J. Crowder
Related to the 'count down to 0', I recently saw another variation, which I thought was clever (if a bit confusing): `for (var i = arr.length; i--; )`
Ryan Kinal
@Ryan: :-) Yeah, I've seen that one (and its cousin, `var i = arr.length; while (i--)...`).
T.J. Crowder
+1  A: 

Here you go:

http://code.google.com/intl/zh-TW/speed/articles/optimizing-javascript.html

tszming
Please don't do link-only answers: http://meta.stackoverflow.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers
T.J. Crowder
Another reason is that a link may be broken after a while.
ring0
+1  A: 

I don't think this is really a performance thing, but something to avoid for sure unless you really know what's happening is:

var a = something.getArrayOfWhatever();
for (var element in a) {
  // aaaa! no!!  please don't do this!!!
}

In other words, using the for ... in construct on arrays should be avoided. Even when iterating through object properties it's tricky.

Also, my favorite thing to avoid is to avoid omission of var when declaring local variables!

Pointy
...or indeed global variables!
bobince
A: 

You will find many examples of what [not] to do in JS in FF, Chrome, Opera etc...
But the current browsers trend/war is focused on speed, and what is true today may not be valid in a year from now.

While it is likely/possible that the optimizations you implement today will still be valid after browsers have been optimized, they may also

  • render the code less easy to read
  • be counter effective as obvious optimizations not performed today (like your example) are likely to be implemented not far from now, and some tricky personal optimizations may disturb the compiler optimizer.

Remember the old Java time, when it was so slow... Now the compiler optimization is much more efficient. Also, in C++, it is often not recommended to perform home optimizations since the embedded optimizer is likely to perform better at that task. (I'm not talking about code structure which is another story)

ring0