The second function should take less time to parse and run than the first, both on page load and when the function is executed.
On page load, the interpreter has to go through all the text, check that its syntax is valid, construct an Abstract Syntax Tree from the result and (on newer engines) compile the result to machine code. Even if most of the a
function body is never executed, it still has to be parsed. Parsing 1 million lines of Javascript is a non-trivial task.
When each function is executed, a
may take more time to run than b
, even if only by a bit - for example, if a
defines many variables inside those lines, variables scoped to a
:
function a() {
var a = false;
if(a) {
var b = 'b';
var c = 'c';
// more lines
}
}
When the function is run, the interpreter has to look through all the variables defined in the if
block which never runs, so that those variable names can be properly initialized. When the function is run, the var b;
and var c
; and any other var
s will be hoisted to the top:
function a() {
var a;
var b;
var c;
// initialize any other variables local to this function
a = false;
if(a) {
b = 'b';
c = 'c';
// more lines
}
}
If there are many variables to initialize, this may result in the function taking a bit longer than if there were no variables to initialize.
In contrast, a function which has no excess variables to initialize nor many lines to parse:
function b() {
var a = false;
if (a != true) {
return;
}
}
will be parsed, compiled, and run more quickly.