A function that reassigns one of its parameters and also uses the special arguments object may not be optimized properly, which could make the program run slower. In particular, the V8 engine (which is used by the Google Chrome browser and the Node.js platform) does not currently perform any advanced optimizations on such functions.
Either eliminate all uses of the
arguments variable, or copy the parameter into a local
variable and reassign that local variable instead.
In the following example, function
sum takes two arguments
start, and returns the sum of all elements in the array
the value of
start. The argument
start is optional and defaults
Observe that to find out whether the argument was provided,
arguments.length (which evaluates to the number of actual arguments passed to
sum), and reassigns
0 if fewer than two
arguments were passed.
In this example, it is easy to eliminate the use of the
arguments variable: instead of
arguments.length, we can instead check whether
A more general solution is to introduce a new local variable, assign the initial value
sum to this local variable, and then update and use the local
variable instead of the parameter:
- Petka Antonov: Optimization killers.