Bad Advice in Pretty Clothing
Bad Advice in Pretty Clothing
A colleague sent around this url:
<
Optimizing JavaScript for Execution Speed>, suggesting that it was a good example could lead people to using the suggestions and thinking that they're all good.
What's wrong with that?
Well, for starters, not all of the examples or reasons are correct. it might be a good article in spirit but some of the advice will mess people up badly.
Minimize Object and Property Lookups
Object-oriented techniques encourage encapsulation by tacking sub-nodes
and methods onto objects. However, object-property lookups are slow, especially if there is an evaluation. So instead of this:
for(var i = 0; i < 1000; i++)
a.b.c.d(i);
Do this:
var e = a.b.c.d;
for(var i = 0; i < 1000; i++)
e(i);
those two examples are not the same, as anyone who has accidentally torn a
method from an object and tried calling it would tell you.
var f = a.b.c;
for(var i = 0; i < 1000; i++)
f.d(i);
would be a generally correct optimization.
Access NodeLists Directly
instead of this:
nl = document.getElementsByTagName("P");
for (var i = 0; i < nl.length; i++) {
p = nl[i];
Do this:
for (var i = 0; (p = document.getElementsByTagName("P")[i]); i++)
But it's wrong at least mostly in its reasoning. The getElementsByTagName most
definitely has to create the nodelist object. As it happens the nodelist object is mostly expensive if it's around to listen for dynamic changes. The right thing to do is probably:
nl = Array.concat(document.getElementsByTagName("P"));
for (var i = 0; i < nl.length; i++) {
p = nl[i];
...
Use Object Literals
he's right.
This saves space and unnecessary DOM references.
but it's not DOM references, just object references.
What should tell you not to suggest a page?
If the page uses markup like this:
By<strong> <a
href="mailto:http://www.websiteoptimization.com/contact">Andy
King</a></strong><br>
Contributing Writer<br>
A footnote about the markup you see above, I write my blog entries in a text
editor in a text format, and use a script to generate html from them,
The link that appears in the document is
By <Andy King>
It should be:
By <Andy King>
And it's a bit hard for me to tell my script
not to treat that url as
somethingelse. I could i suppose teach it how to mishandle links in a manner
similar to the way that the site I'm quoting did, but I'm not sure why I'd
want to. mailto:http: isn't proper,
ever. it's mailto:user@host. If you want
to say that contact may be made by following an http link, then say so.