I quite often have optional arguments in functions, but some testing is showing a huge performance hit for them in firefox and safari (70-95%). Strangely, if I pass in the liter
I think what could explain the performance difference is the way arguments are passed to a function object: via the arguments
object. When not passing any arguments, JS will start by scanning the arguments object for any of the given arguments, when those are undefined, The arguments
prototype chain will be scanned, all the way up to Object.prototype
. If those all lack the desired property, JS will return undefined
. Whereas, passing undefined explicitly, sets it as a property directly on the arguments object:
function foo(arg)
{
console.log(arguments.hasOwnProperty('0'));
}
foo();//false'
foo('bar');//true
foo(undefined);//true
I gather that's the reason why passing undefined explicitly tends to be faster.