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:
var
statements;var
s as possible...and disadvantages:
arguments
can be altered in unexpected ways. See belowStill 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.
No, don't do this. It's confusing and unnecessary. And I find your list of "advantages" to be quite specious - every item on there is very thin as to the actual benefit gained.
If you must, just use the comma operator and declare all your variables in a single statement right at the head of the function (they're hoisted to this spot anyways.
function howManyMatch(arr, pattern) {
var i, l, total;
// rest
}
Or you can declare/define all in once step too
function howManyMatch(arr, pattern) {
var l = arr.length, total = 0, i = 0;
// rest
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With