1

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.

2
  • 1
    "By performance I of course mean execution performance (including lookup, scope traversal, etc..) " There is none. Both definitions create the same kind of function object. Commented Jan 28, 2015 at 6:39
  • The only performance issues I could think of is from using NFE's in certain engines — kangax.github.io/nfe/#jscript-memory-management Commented Jan 28, 2015 at 13:10

2 Answers 2

1

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:

Sign up to request clarification or add additional context in comments.

4 Comments

I literally googled for this everywhere both today and yesterday, skimming through many articles on the web. Yet somehow I completely forgot about checking for a jsperf. Also thanks for the short summary in your answer. +1, accepted
Well, a function declaration in a loop would be a syntax error, so you don't really have that choice.
@BjornTipling: Use strict mode, and possibly a browser that doesn't know quirky function statements
I was confused by the "Function declaration & expression" in that test, until I realized it's a poor, misunderstood named function expression...
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.