Home > database >  Memory allocation on bound method vs unbound method
Memory allocation on bound method vs unbound method

Time:12-29

From the doc:

Class fields are defined on the instance, not on the prototype, so every instance creation would create a new function reference and allocate a new closure, potentially leading to more memory usage than a normal unbound method.

Class fields (arrow function) leads to more memory usage than unbound method. But how it allocates with bound methods?

class C {
  a = 1;
  constructor() {
    this.boundMethod = this.boundMethod.bind(this);
  }
  boundMethod() {
    console.log(this.a);
  }
  unboundMethod() { }
  classField = () => {
    console.log(this.a)
  }
}

So, I need more clarification on this:

  • class field allocates more memory than unbound method.

But what does it with bound method? Is same memory allocated as class field?

CodePudding user response:

There's not really a difference between creating properties in the constructor

class C {
  constructor() {
    this.a = 1;
    this.boundMethod = this.boundMethod.bind(this);
    this.classField = () => {
      console.log(this)
    };
  }
  boundMethod() {
    console.log(this.a);
  }
  unboundMethod() { }
}

and using class fields:

class C {
  a = 1;
  boundMethod = this.boundMethod.bind(this);
  classField = () => {
    console.log(this)
  };
  boundMethod() {
    console.log(this.a);
  }
  unboundMethod() { }
}

They do the same and have the same memory usage. As for the arrow function vs the bound function, both construct a new function object per C instance, whether they have the same memory size (in bytes) or not depends on the JS engine.

CodePudding user response:

But what does it with bound method? Is same memory allocated as class field?

According to the spec, a new function is created for every invocation of Function.prototype.bind() — so, for every instance of the class that is instantiated, a new function should be created.

Whether this actually results in greater memory allocation is not defined in the spec, and will depend on the implementation of the JavaScript runtime that you are using to execute your code. You will need to profile the memory usage of your code in tests to determine the allocation behavior of a specific runtime.

  • Related