const carFactory = (brand, seats) => ({
brand,
seats,
sound: () => console.log("wrooom")
})
for(let i = 0; i < 20; i++) {
carFactory(`brand-${i}`, 5)
}
class Car {
brand;
seats;
constructor(brand, seats) {
this.brand = brand;
this.seats = seats;
}
sound() {
return console.log("wrooom")
}
}
for(let i = 0; i < 20; i++) {
new Car(`brand-${i}`, 5)
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Create object by function | |
Create object by class |
Test name | Executions per second |
---|---|
Create object by function | 9883335.0 Ops/sec |
Create object by class | 1731881.6 Ops/sec |
Benchmark Overview
The provided JSON represents a benchmark test created on MeasureThat.net, comparing the performance of two approaches to create objects in JavaScript: using an arrow function versus creating a class instance.
Options Compared
Two options are compared:
const carFactory = (brand, seats) => ({ ... })
) to create an object.class
keyword (e.g., class Car { ... } new Car(
brand-${i}, 5)
).Pros and Cons of Each Approach
this
binding.Library Used
None of the provided benchmark definitions explicitly uses a library. However, it's worth noting that MeasureThat.net is a JavaScript benchmarking platform that may use libraries or frameworks under the hood to execute the benchmarks.
Special JS Feature or Syntax
The benchmark test utilizes ES6-style classes and arrow functions, which are part of the ECMAScript standard. The class
keyword was introduced in ECMAScript 2015 (ES6), while arrow functions were also introduced in the same specification.
Benchmark Preparation Code
The benchmark preparation code is not provided, but it's likely that MeasureThat.net generates a script that creates an array of objects with varying properties and executes the benchmarks multiple times to gather statistics.
Other Alternatives
To create objects in JavaScript, developers may use other approaches, such as:
function Car(brand, seats) { ... }
).new
keyword with a function expression (e.g., new Car(
brand-${i}, 5)
).These alternatives may have different performance characteristics and trade-offs compared to arrow functions or class instances.