I caught this article on Reddit this weekend and had definite mixed feelings about it. Many of their suggestions were obviously good ideas—calling SetTimeout() with a string is obviously stupid, as are 90% of the possible uses of eval() and Function(). The advice on what causes the DOM to repaint and reflow was interesting and informative.
It would have been a really good article except that some of their advice seemed weak. Some of what was masquerading as optimization “advice” seemed more like work-arounds for a substandard javascript implementation.
Take this for example:
var min = Math.min(a,b); A.push(v);
These alternatives provide the same functionality, while performing better:
var min = a < b ? a : b; A[A.length] = v;
Yes, I can see in someone’s world that might perform better. But come on, the compiler/scanner should be able to produce the equivalent code. Anything less is a failing of your browser and not an “unoptimized” program. Do you really expect people to crappify their programs because your browser can’t properly optimize javascript for you?
“Well,” I hear you say, “it’s interpreted, not compiled.” To which I say, yeah, well there’s your first problem. Fix that before telling me that I need to use stupid constructs to make my program go fast.
Here’s another example:
This example requires the script engine to create 21 new string objects, once for each time the length property is accessed, and once each time the charAt method is called:
var s = '0123456789'; for( var i = 0; i < s.length; i++ ) { s.charAt(i); }
This equivalent example creates just a single object, and will perform better as a result:
var s = new String('0123456789'); for( var i = 0; i < s.length; i++ ) { s.charAt(i); }
Again, this strikes me as being a failing of the compiler. I see no reason why the browser should instantiate a string object just to call its length(). A little bit of hard coding in your implementation can optimize that to a strlen() call or better—No object instantiation at all. What if someone overrode String.prototype.length()? That’s one if statement in C and some fallback code. Again, I don’t think my program should suffer because your browser doesn’t properly optimize things.
But then again, maybe I’m just crazy.