Javascript inner functions and closures performance in Node.js
##Tested on
Node v0.12.0
AMD-FX 8130
10GB RAM
Each test was run 5 times and the average time was taken
##Why I would prefer the version with the closure
(+) Because it avoids repeating the function parameters in every other function -a,b- gets repeated twice when not in closure
(+) Because it creates a lexical scope, code isolation and code organization, the bar function is encapsulated which makes sense if I do not plan to use this function elsewhere
(-) Unit testing is a little bit more complicated but doable. Not that in this case you do not always need to test the bar function if it is large. Sometimes it is enough to test the foo function as it is the only one which can be used elsewhere.
##Performance
Function
Exec Time
foo
3300 ms
foo1
2400 ms
foo2
400 ms
foo3
3300ms
foo4
400ms
foo5
19000ms
foo6
570ms
Looks like inner functions/closures in this scenario are 5X->10X slower. No difference between functions declarations vs anonymous functions.
Functions declarations vs anonymous functions have the same time -> V8 optimizes by only compiling once the function code.
Note this is an extreme testing, not really a real life scenario. You app will usually spend more time calling http services, databases, etc… It is not frequent to call so many functions in a web app to serve a request
#Scala equivalent
Scala 2.11.5
##Performance
Function
Exec Time
foo
600 ms
foo1
600 ms
foo2
600 ms
Performance remains the same
#Python equivalent
CPython 2.7.6
While Scala runs on the JVM -compiled to bytecode then JIT compiler- and V8 compiles directly to assembler code using 2 compilers -a fast one and an optimzer-, Python is interpreted, so we can expect it to run much slower