Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a performance hit of replacing local variables with arguments in Javascript?

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 var statements;
  • less programmer time spent trying to use as few vars as possible
  • all local vars defined in one place

...and disadvantages:

  • arguments can 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.

like image 478
Steve Clay Avatar asked Dec 06 '10 20:12

Steve Clay


1 Answers

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
}
like image 100
Peter Bailey Avatar answered Oct 14 '22 21:10

Peter Bailey