JavaScript Performance – Anonymous Functions and setTimeout

javascriptperformance

According to Gregory Baker & Erik Arvidsson (Google), creating a named function and then passing that to setTimeout is actually faster than creating an anonymous function (reference: Optimizing JavaScript code -> Avoiding pitfalls with closures):

Creating a closure is significantly slower then creating an inner function without a closure, and much slower than reusing a static function. For example:

<snip>

    function alertMsg() {
      var msg = 'Message to alert';
      alert(msg);
    }

is slower than:

    function setupAlertTimeout() {
      window.setTimeout(alertMsg, 100);
    }

In my testing, there does not appear to be any significant difference (jsPerf here), so why do they claim that creating a whole named function is faster than simply making an anonymous function?

EDIT: note that I am specifically referring to the last two examples, the first one has been removed for clarity.

Best Answer

The theoretical difference comes from the fact the named function in your example is created at "compile" time.

But the real truth is that JavaScript engines are now very very good at creating and managing functions and scopes, which is arguably one of the most critical topic with today's coding style, so the overhead is generally totally insignificant.

In my opinion, this particular advice creates more harm (over optimized code) than good today. I see it as obsolete.