0

I was surprised to run these tests and see that a singly-defined function statement was so much more performant than a singly-defined function expression:

function tests

I wasn't too surprised to see that the inner anonymous function was so slow, since I reasoned it was build on every iteration of the loop. But what is it about the difference between function expressions and statements which makes such a noticeable difference? And why is this difference so profound in Chrome?

enter image description here

jackweirdy
  • 5,632
  • 4
  • 24
  • 33
  • 1
    What other Javascript engines have you tried? Your screenshot says Chrome, but that's only one data point. I just tried Firefox and it gives completely different performance numbers. – Greg Hewgill Jul 21 '14 at 00:18
  • 1
    http://stackoverflow.com/questions/5433883/function-declaration-faster-than-function-expression – adeneo Jul 21 '14 at 00:21
  • I ran it in Firefox and IE also, which shows more reasonable differences. So, it comes down to; what did Chrome do wrong? – Guffa Jul 21 '14 at 00:21
  • Safari also shows very differently--the two which do not use IIFE are almost identical. – JAAulde Jul 21 '14 at 00:22
  • 1
    What you are calling a "function statement" is a function declaration, very few browsers implement function statements (Firefox is one), and there are none in the OP. The "anonymous function" is an immediately invoked function expression that must be parsed and evaluated each time, so of course it's slower than a declared function that is parsed only once. – RobG Jul 21 '14 at 00:33
  • Be careful of random tests on jsPerf. A test of [*4 different methods*](http://jsperf.com/function-creation-tests) of creating functions shows that they create functions that all run at about the same speed. – RobG Jul 21 '14 at 01:03
  • @Guffa yes, that's the question I'd like answered; what is it about Chrome's execution strategy that makes this so costly? – jackweirdy Jul 21 '14 at 08:20
  • This has been closed because it's a duplicate, but I've altered it to be more specific and nominated it to be opened. Also note that the answers on the other question don't answer it. – jackweirdy Jul 21 '14 at 08:25

0 Answers0