javascript V8 optimisation and “leaking arguments”

前端 未结 2 685
花落未央
花落未央 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 15:54

    This is a 2-fold problem:

    1. You lose any and all possible optimizations and branch predictions
      The arguments object is unpredictible.
    2. You leak memory. Really bad!

    Consider the following code (run it at your own risk!):

    function a(){return arguments;}
    
    x=a(document.getElementsByTagName('*'));
    
    window._interval=setInterval(function(){
    
        for(var i=0;i<1e6;i++)
        {
            x=a(x);
        }
    },5000);
    *{font-family:sans-serif;}

    Warning! This may overheat your cpu and crash your browser really badly!

    I'm not responsible for any software and hardware damages!

    Run at your own risk!!!

    If you ran this code, press F5 to stop or close the browser.

    If you want, you can try to . (the RAM may remain unchanged)

    And now watch your RAM go up, when you run that (it goes up at a rate of around 300-500MB every 5 seconds).
    A naive implementation that simply passes the arguments around may cause these problems.

    Not to mention that your code will (generally) be a tad slower.


    Note that this:

    function a(){return arguments;}
    function b(arg){return arg;}
    
    x=a(document.getElementsByTagName('*'));
    
    window._interval=setInterval(function(){
    
        for(var i=0;i<1e6;i++)
        {
            x=b(x);
        }
    },5000);
    *{font-family:sans-serif;}

    This may be safe, but be careful!

    I'm not responsible for any software and hardware damages!

    Run at your own risk!!!

    If you ran this code, press F5 to stop or close the browser.

    If you want, you can try to .

    Won't have the same effect as the code before.
    This is because b() returns the same variable, instead of a new reference to a new arguments object.
    This is a very important difference.

提交回复
热议问题