javascript V8 optimisation and “leaking arguments”

前端 未结 2 689
花落未央
花落未央 2021-02-06 15:13

I read in various places that it\'s advisable to be careful with the arguments object and that this is ok...

    var i = arguments.length, args = ne         


        
2条回答
  •  星月不相逢
    2021-02-06 16:01

    The problem with arguments is same as with local eval and with: they cause aliasing. Aliasing defeats all sorts of optimizations so even if you enabled optimization of these kind of functions you would probably end up just wasting time which is a problem with JITs because the time spent in the compiler is time not spent running code (although some steps in the optimization pipeline can be run in parallel).

    Aliasing due to arguments leaking:

    function bar(array) {    
        array[0] = 2;
    }
    
    function foo(a) {
        a = 1;
        bar(arguments);
        // logs 2 even though a is local variable assigned to 1
        console.log(a);
    }
    foo(1);
    

    Note that strict mode eliminates this:

    function bar(array) {    
        array[0] = 2;
    }
    
    function foo(a) {
        "use strict";
        a = 1;
        bar(arguments);
        // logs 1 as it should
        console.log(a);
    }
    foo(1);
    

    Strict mode however isn't optimized either and I don't know any reasonable explanation except that benchmarks don't use strict mode and strict mode is rarely used. That might change since many es6 features require strict mode, otoh arguments is not needed in es6 so...

提交回复
热议问题