<script>
// Define the EmptyClass
class EmptyClass {
EmptyClass(a, b) {
this.a = a;
this.b = b;
}
}
var resulting = {
instance: null
};
</script>
const instance = new EmptyClass(1,2);
resulting.instance = instance;
const instance = Object.create(EmptyClass);
instance.a = 1;
instance.b = 2;
resulting.instance = instance;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
new EmptyClass | |
Object.create(EmptyClass); |
Test name | Executions per second |
---|---|
new EmptyClass | 186718672.0 Ops/sec |
Object.create(EmptyClass); | 66215348.0 Ops/sec |
The benchmark defined by MeasureThat.net is designed to compare two different methods of creating instances of a class in JavaScript: using the new
keyword with a class constructor and using Object.create()
with an existing class. Here's a breakdown of what is tested and the considerations involved.
This benchmark evaluates two approaches to instantiate a JavaScript object and measure their performance.
Test Name: new EmptyClass
const instance = new EmptyClass(1,2);
resulting.instance = instance;
new
keyword to create a new instance of EmptyClass
, passing two parameters (1
and 2
). It relies on JavaScript's class syntax introduced in ECMAScript 6 (ES6).Test Name: Object.create(EmptyClass);
const instance = Object.create(EmptyClass);
instance.a = 1;
instance.b = 2;
resulting.instance = instance;
Object.create()
to create a new object that has its prototype set to EmptyClass
. It manually assigns properties a
and b
to the newly created object.Using new EmptyClass
EmptyClass
) can enforce any logic, such as property initialization and validation during instantiation.Using Object.create(EmptyClass)
In this benchmark, there isn’t any specific library being tested; it focuses solely on core JavaScript features. One notable feature used is the class syntax introduced in ES6, which allows for cleaner and more structured object-oriented programming compared to the traditional prototype-based approach.
Other alternatives to object creation in JavaScript could include:
new
keyword was standard, but it lacked many syntactic conveniences of classes.This benchmark is a clear examination of how different object instantiation approaches affect performance. It is particularly relevant in a context where performance is critical, and developers must choose between readability and efficiency, or between idiomatic class-based patterns and classic prototypal inheritance methods. Understanding these differences helps software engineers make informed decisions based on application needs, performance constraints, and coding style preferences.