Given the following two:
Scenario 1
function inner() {
// a bunch of code that does stuff
}
function outer() {
inner();
}
for(var i = 0; i < 10000; i++) {
outer();
}
Scenario 2
function outer() {
function inner() {
// a bunch of code that does stuff
}
inner();
}
for(var i = 0; i < 10000; i++) {
outer();
}
Behavior is identical in both cases, no doubt. But what’s the difference under the hood? How much extra work, if any, is the interpreter doing in scenario 2? Is the memory affected. Or, say, if the body of inner() gets longer, would that increase the effect on performance?
Please don’t bother asking “why would you want to do that”, because my question is not about a practical issue. Just trying to get a deeper understanding of how JS function are parsed and represented. Thanks!
It depends entirely on the JavaScript engine. (I don’t call them “interpreters” any more, because so many of them actually compile on the fly.)
In theory, the engine might re-interpret/re-compile
innerupon every entry intoouter. Or at least, allocate a newinnerfor every call toouter.The more likely scenario, with modern engines, is the code for
inneris only compiled once, and reused, and a new function object is created for each call toouterwhich reuses that code with different execution context. The impact of this is negligible (consider how often you write{}in your JavaScript functions without worrying about the impact of creating an object). Certainly that’s what V8 (the engine in Chrome) does in most situations, and almost certainly what most modern engines do.