Javascript memory implication of nested arrow functions

Viewed 257

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 memory implications of calling f1 and f2.

Regarding n11, this answer says:

For some very small and normally inconsequential value of "wasted". JavaScript engines are very efficient these days and can perform a wide variety of tricks/optimizations. For instance, only the function-object (but not the actual function code!) needs to be "duplicated" internally. There is no "wasting" problem without an actual test-case that shows otherwise. This idiom (of nested and anonymous functions) is very common in JavaScript and very well-optimized for.

However I want to know if this also apply to arrow functions (ie n12, n21 and n22) .. will the overhead only be a function-object as above or will the entire nested function code be duplicated every time f1/f2 are called ?

thx!

1 Answers

There's absolutely no reason why an implementaton would need to do anything different for arrow functions than traditional functions with regard to the sharing of code between different closures of the same function. The only difference between arrow functions and traditional functions is that arrow functions save the this value. This can be done using the same mechanism as is already provided for the Function.prototype.bind() method. An arrow function is mostly just syntactic sugar.

func = () => { body };

is roughly equivalent to:

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

(This is a slight simplification, since arrow functions also don't get an arguments object, but that shouldn't affect what you're asking.)

Related