Is there any performance hit for writing a function such that local var statements are replaced with arguments? Example:
function howManyMatch(arr, pattern, /*ignored:*/ i, l, total) {
l = arr.length;
total = 0;
for (i = 0, i < l; i++) {
if (pattern.test(arr[i]))
total++;
return total;
}
Some advantages:
- smaller minified size: no
varstatements; - less programmer time spent trying to use as few
vars as possible - all local vars defined in one place
…and disadvantages:
argumentscan be altered in unexpected ways. See below- less clear in body that vars are local
- confusing to see arguments that don’t do anything
- if someone unknowingly removes them, your code writes to globals
Still it might be an easy way for a minifier to automatically squeeze out more bits.
Update: a big disadvantage not mentioned so far: If a function is called with N parameters, the first N items in arguments will be binded to the first N identifiers in the argument list (see the last bullet in 10.1.8). Consider this:
function processStuff(/*ignored:*/i, j, k) {
// use i/j/k to loop
// do stuff with the arguments pseudo-array
}
In the above example, if you called processStuff(stuff1, stuff2), setting i and j would overwrite arguments[0] and arguments[1] respectively.
I wouldn’t do it for many of the reasons you already know, personally I don’t like the fact of mixing the semantic meaning of arguments vs. variables, although at the implementation level, when the function is executed, they are just properties of the current variable object, they have different meaning IMO.
Now, answering the question, I don’t think there’s any performance impact.
Let me talk a bit about the the Variable Instantiation process, it takes place for Function Code, just before the function is executed (commonly known as “hoisting”), at first, all the Formal Parameters described for the function are bound to the current Variable Object (the current scope), and they are initialized with the values passed in the function call or
undefinedif not supplied.After that, all the identifiers that belong to all
varstatements within the function are declared in the current scope, and initialized withundefined(note that the assignments are made after this, the function body isn’t actually being executed yet).The third step are FunctionDeclarations, all the identifiers of function declarations are bound to the local scope, if an identifier was previously declared, its value is replaced, for example:
I would recommend instead simply to use a single
varstatement, at the top of the function:That doesn’t just organize your code, it would help you to prevent unwanted results due the function-only scope of JavaScript and the “hoisting” nature of
var, some tools like JSLint encourage this also.