Skip to content Skip to sidebar Skip to footer

Function Declaration And Function Expression Performance Difference

I have used JSperf to test a small sample of code. According to a few articles I came across, both should have similar performance with test2 having a little edge. But here it's t

Solution 1:

With the powerful optimizations JavaScript engines are using these days, Micro-benchmarks like this produce somewhat misleading results. For example, I'm guessing what you were trying to measure is function call overhead. But it looks like the way your code is written, you may be (re)defining the function definition and/or symbol lookup once for every 10 times you execute it; I'm guessing that wasn't the intent.

In this alternative test, I've arranged things to avoid repeated definition of the function, and added a few other ways of invoking the functions. This reduces the difference in performance to something I'd consider dominated by experimental noise. While this there may sometimes be apparent differences but I wouldn't consider them statistically significant given the experimental error levels. In other words, it reduces the contest to a virtual tie.

Even in browsers where there's a consistent difference between approaches, caching the function in a local variable seems to minimize the difference between definition and expression.


Solution 2:

I also understand the differences between both of them.

Do you also understand these semantic differences?

Notice that jsPerf puts your code inside a tight loop whose execution time is measured. The function declaration requires the creation of a block scope for each iteration, which slows the test down considerably. That is hardly what you were trying to measure.


Post a Comment for "Function Declaration And Function Expression Performance Difference"