Javascript arrow nested memory implication

Consider:

function f1() { function n11() { .. lots of code .. }; const n12 = () => { .. lots of code .. }; return n11()+n12()+5; } const f2 = () => { function n21() { .. lots of code .. }; const n22 = () => { .. lots of code .. }; return n21()+n22()+5; } 

I am trying to understand the consequences of memory for calling f1 and f2.

Regarding n11, this answer says:

For a very small and usually insignificant value, "wasted." These days, JavaScript engines are very efficient and can perform a wide variety of tricks / optimizations. For example, only a function-object (but not the actual function code!) Should be "duplicated" domestically. There is no problem of “exhaustion” without an actual test case that shows otherwise. This idiom (nested and anonymous functions) is very common in JavaScript and is very well optimized for.

However, I want to know if this also applies to arrow functions (i.e. n12, n21 and n22) .. whether the overhead will only be a functional object, as indicated above, or will all the nested function code be duplicated every time f1 / are f2 called?

THX!

+5
source share
1 answer

There is absolutely no reason why to implement arrow functions, you would need something different for arrow functions than traditional functions with respect to sharing code between different closures of the same function. The only difference between arrow functions and traditional functions is that arrow functions retain this value. This can be done using the same mechanism that is already provided for the Function.prototype.bind() method. The arrow function is basically syntactic sugar.

 func = () => { body }; 

approximately equivalent:

 func = function() { body }.bind(this); 

(This is a slight simplification, as arrow functions also do not receive the arguments object, but this should not affect what you ask.)

+5
source

Source: https://habr.com/ru/post/1272055/


All Articles