There are already a few Q&A regarding the class
OOP is various languages.
It appears that static
method is marginally faster than Instance method but the difference is insignificant in common practical usage.
ref:
Performance of using static methods vs instantiating the class containing the methods
Speed Test: Static vs Instance Methods
In class instance example, 2 objects are created, the original
class
and a clone also usingnew
.
(If there is a situations where multiple processes with different data need to set values and use the same class at the same time, then creating anew
clone for each process would maintain data integrity.)In
static
example, only one object is created.
Are there any benefits to consider when deciding between the two types?
For example:
// class instance
class Triple {
do(n = 1) {
return n * 3;
}
}
const triple = new Triple();
triple.do(5); // 15
// static method
class Triple {
static do(n = 1) {
return n * 3;
}
}
Triple.do(5); // 15
Update constructor
issue
It seems that the constructor
only works in class
instance.
ref:
How do I use a static variable in ES6 class?
Example:
// class instance
class TriplePlus {
constructor() {
this.a = 10;
}
do(n = 1) {
return (n * 3) + this.a;
}
}
const triplePlus = new TriplePlus();
triplePlus.do(5); // 25
// static method
class TriplePlus {
constructor() {
this.a = 10;
}
static do(n = 1) {
return (n * 3) + this.a;
}
}
TriplePlus.do(5); // NaN
Update for clarification (re comments)
Please note that above are simplified concept examples. The actual class has 10s of methods. A typical example for the static
in class is a set of utility methods which perform better as OOP in a single object vs multiple individual factory functions. The focus of the topic is the comparison between class Instance vs Static. The discussion about factory function alternatives is irrelevant to this topic.
The
static
keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.