Performance penalty for undefined arguments

前端 未结 2 635
逝去的感伤
逝去的感伤 2021-02-08 09:41

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

2条回答
  •  抹茶落季
    2021-02-08 10:35

    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.

提交回复
热议问题