Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performance and memory footprint of arrow functions [duplicate]

With ES6 javascript offers the use of arrow functions like:

var quadr= x => x * x;

I know this influences the binding of this, arguments, super and new.target. source

This is certainly usefull to ensure a correct this in every scope. But i'm questioning if the binding affects the memory footprint of the script. Are less objects in the execution context? Does this influence the performance of the functions?
And what happens (qua memory and allocation) when we reference a this inside an arrow function, like:

function person(){
  this.age=0;
  //it's my birthday so...
  ()=>{
     this.age++;
  }
}
like image 399
Bee157 Avatar asked Nov 23 '25 16:11

Bee157


1 Answers

And what happens (qua memory and allocation) when we reference a this inside an arrow function?

Whenever a function is called, a lexical environment is created, which has a reference to the lexical environment in which it was defined. So imagine this:

function a(){
  function b(){
  }
  b.call(bContext)
}
a()

the lexical environments have a value pointing to the current context (aka this), and a reference of their enclosing lexical environment. so if the inner function gets called the environment would look like this (pseudocode):

a{
  this:window
}
b{
 parent:a
 this:bContext
 }

Lets imagine b would be an arrow function:

function a(){
  b=()=>{};
  b();
}

then there would simply be no context in it, and it would be looked up in a's environment:

a{
  this:window//
}
b{
 parent:a
 }

Therefore, arrow functions are actually a bit more leightweight then the regular ones.

like image 181
Jonas Wilms Avatar answered Nov 25 '25 09:11

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!