Wingblade
Wingblade

Reputation: 10093

Function declaration vs expression from a performance point of view?

There's many javascript articles on the web comparing function declarations function foo (){} to function expressions var foo = function () {}. They usually mention things like hoisting, behaviour within conditionals, etc... But I don't recall any of them talking about performance. Is there any difference? Particularily in ECMA5's strict-mode (if that changes anything).

By performance I of course mean execution performance (including lookup, scope traversal, etc..) not declaration performance, although that would be a nice-to-know aswell.

Upvotes: 1

Views: 1005

Answers (2)

Bjorn
Bjorn

Reputation: 71830

Function declarations are faster in cases where there's a potential for the function expression to be evaluated multiple times. For example, in code that is called in a loop a hoisted function is only evaluated once, but an expression would be evaluated each time. Besides that, there's no meaningful difference.

Whenever you have a question about a JavaScript performance issue, I recommend checking out JSPerf. Also, Google to see if someone already made one for your question:

Upvotes: 1

deblocker
deblocker

Reputation: 7677

I executed the same tests from JSPerf in Chrome canary 45 and Firefox 37, sadly the results are opposite:

function myfunc() {
  alert("yo");
}
myfunc();

Chrome: fastest, FF: much slower

var myfunc = function() {
    alert("yo");
    }

myfunc();

FF: fastest, Crome: much slower

So, the answer is: it depends from the browser/JS engine.

Upvotes: 0

Related Questions