Greetings.
I came across an interesting article about bad practices for optimizing code in JS engines.
I wondered why arguments flow in the cases described and why Function#apply is an exception.
It is especially interesting why there will be a leak with Array#slice , because when transmitting primitives, an unrelated copy will be returned.
Thank you for attention.

1 answer 1

What does the leak, if the article about the "killer optimization"?

In fact, everything is simple.

 function foo(x, y, z) { bar(arguments); console.log(x, y, z); } foo(1, 2); 

Let's play the game. You are a js compiler. What are the x, y and z variables at the end equal? Without the bar function, this will not work.

Now another problem:

 function bar(a) { a[0] = 6; a[1] = 7; a[2] = 8; } function foo(x, y, z) { bar(arguments); console.log(x, y, z); } 

What can we say now? The console output is still undefined!

The arguments object makes the function very difficult to compile - in order to learn at least something, you have to dig very deep. Therefore, it is easier not to try to optimize such functions.


The decision, in fact, is much simpler than what is written in that article.

"use strict"

  • Yes, I know that, but what about Array#slice and Function#apply ? - user207618
  • @Other is the same external function as the rest. They can, for example, zamankipatchit. - Pavel Mayorov
  • 2
    Even if you do not skip it, it will not be optimized. To pass arguments as a parameter, you need to match it (in an optimized version of arguments completely absent, values ​​are stored in a stack (see the article on v8)). Creating an arguments object can be an expensive operation (if the code is “hot”). "use strict" resolves only some problems with arguments (removes the need to update the value in arguments when the corresponding named argument is changed). - Arnial
  • Function.prototype.apply is a special case (he, by the way, also has pitfalls). (Further, only my assumptions) I suppose that if apply is called for arguments, you can simply copy the stack of the current function to the called function, of course you will need to change some values ​​(note the current this), but this will be faster than creating an arguments object (and then deleting it have to (gc)). - Arnial