3 ms·
Since classes are just sugar over prototypes, their performance is just about the same for instantiation. I assume the article is comparing them to functions th
by rhinoceraptor 9y ago
Since classes are just sugar over prototypes, their performance is just about the same for instantiation. I assume the article is comparing them to functions that return an object literal with methods.
Here is a simple example of equivalent code in a class, function with a closure, and a prototype:
class FooClass {
constructor (bar) { this.bar = bar; }
getBar () { return this.bar; }
setBar (bar) { this.bar = bar; }
}
function FooClosure (bar) {
var _bar = bar;
return {
getBar () { return _bar; },
setBar (bar) { _bar = bar; }
};
}
function FooPrototype (bar) { this.bar = bar; }
FooPrototype.prototype.getBar = function () { return this.bar; };
FooPrototype.prototype.setBar = function (bar) { this.bar = bar; };
When instantiating a lot of objects, the prototype and class are practically the same, but the function closure pattern is a lot slower. On my machine, instantiating one hundred million of the class or prototype each took about 500ms, but the closure function took about 3s.