nimo23
nimo23

Reputation: 5680

"static method" vs "object property method"

What is the difference in relation to performance between this:

Version 1:

export default class User {

  static getList(data) {
   ...
  }

  static getItem(data) {
   ...
  }

}

and this:

Version 2:

export default {

  getList(data) {
   ...
  },
  getItem(data) {
  }
  ...

}

Both are called directly:

import User from "./User";
User.getList(data); // by static method (version 1)
User.getList(data); // by object property method (version 2)

So where lies the difference?

Upvotes: 2

Views: 95

Answers (1)

Felix Kling
Felix Kling

Reputation: 816334

Static methods are simply properties of the constructor function object. So the difference would be that in the first case you are creating a function object (the constructor) and in the second case you are creating a "plain" object. I.e. simplified:

var firstExample = Object.assign(function() {}, {
  getList() {},
  getItem() {},
});
var secondExample = Object.assign({}, {
  getList() {},
  getItem() {},
});

You should use what makes the intention of your code clear. If you are never going to actually instantiate User then you shouldn't use a class for that.


Does the static method ("version 1) is only created once while the other object ("version 2") is cloned (?) every time when it s called?

No. In both cases the methods are only created once.

Does the class has overhead where object does not?

Probably. Creating a "class" involves more steps than creating an object. That however won't have any real performance on your application.

Upvotes: 2

Related Questions