As a developer in a large and fast growing environment you are always thinking about new ways to improve performance and code maintenance. To speed up and optimize both, you can try the following:

Whenever you want to execute JavaScript that isn’t wrapped by a class or a named function, think about using anonymous functions!

Example:

<script type="text/javascript">//<![CDATA[
var element = $("important-element");
// ...
// Anonymous function
(function() {
  var element = $("element-id"), foo = true;
  element.observe("click", function(event) {
    event.stop();
    someFunction(element, foo);
  });
})();
console.log(element); // still the "important-element"
//]]></script>

Well, this looks strange, doesn’t it?
But there are at least two really interesting points why you should decide to do this in the future:

  • First, an anonymous function opens its own local scope. This means you cannot access the locally declared variable “element” or “foo” (example above) from outside of the function and this also means that you don’t have to be worried that your code overwrites variables which are declared in the global scope (i.e. “Prototype”, “Event” or the other “element” variable from above).
  • The second thing is performance. Code which is executed in a small local scope will definitively perform faster than in the global scope.

Don’t believe it?

Then open your firebug console and execute these two examples:

Slow:

var time = new Date();
for (var i=0; i<25000; i++) { var foo, bar, test; }
var duration = (new Date()-time);
console.log("It took " + duration + " ms");

Up to 20 times faster (tested in FF 3 on Mac):

(function() {
  var time = new Date();
  for (var i=0; i<25000; i++) { var foo, bar, test; }
  var duration = (new Date()-time);
  console.log("It took " + duration + " ms");
})();

Man, that’s what people call low investment, high return!


1
Comment
Leave a comment
marko on 11.12.2008 at 11:55h CET

The speed improvement isn’t very convincing.

In Safari 3.2.1 I can obsorve no speed difference at all. With TraceMonkey, SquirrelFish or V8 it could be totally different again - in either direction.

So I deem the speed of anon functions as being highly platform dependent. Or do you have other evidence?

RSS-Feeds RSS feed for comments on this post.

Leave a comment

If you have a Word Press Account, please sign in