The Managing arguments section in Bluebird's article on Optimization killers states that:
The
argumentsobject must not be passed or leaked anywhere.
In other words, don't do the following:
function leaky(){
return arguments;
}
But do do this:
function not_leaky(){
var i = arguments.length,
args = [];
while(i--) args[i] = arguments[i];
return args;
}
With the introduction of Rest paramters, will passing the rest parameter array still cause optimization issues? From what I am understanding, the issue is that we can't let the actual arguments Object get loose. Finite, defined copies of arguments are OK, but not the actual Object itself. If that is the case, is the rest argument treated as an OK and optimizable copy of arguments when used in the following way?
function maybe_optimizable(...args){
return args;
}
Specifically, I'm trying to write a debounce function based on David Walsh's debounce function (which is based on Underscore.js') and I believe there is an issue with assigning arguments to a variable within the top scope of the debounce function. To rectify this I wrote the following:
function debounce(func, wait, immediate) {
let timeout;
return function (...args) {
let context = this,
now = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(() => {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
}, wait);
if (now) {
func.apply(context, args);
}
};
}