function test1(mixin) {
return {
a: 'a',
b: 'b',
c: 'c',
d: 'd',
e: 'e',
f: 'f',
mixin
};
}
class Test2Class {
constructor() {
this.a = 'a';
this.b = 'b';
this.c = 'c';
this.d = 'd';
this.e = 'e';
this.f = 'f';
}
}
Test2Class.prototype.ok = function () {
return 'ok';
};
function test2() {
return new Test2Class();
}
const obj1 = test1({ ok: () => 'ok' });
obj1.ok() === 'ok'
const obj2 = test2();
obj2.ok() === 'ok'
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
test1 | |
test2 |
Test name | Executions per second |
---|---|
test1 | 6940631.0 Ops/sec |
test2 | 30670514.0 Ops/sec |
Let's dive into the details of this JavaScript microbenchmark.
Benchmark Overview
The benchmark measures the performance difference between two approaches to create and use objects with methods. The benchmark is designed to test the execution speed of object creation, method invocation, and comparison.
Options Compared
There are two options being compared:
test1
function: This function creates an object by concatenating a literal object with the mixin
parameter using the spread operator (...
). It also defines a method ok()
on the resulting object.test2
class: This class creates an instance of itself, which automatically sets up the properties and methods defined in the constructor.Pros and Cons
test1
function:test2
class:Library
None. This benchmark doesn't use any external libraries or frameworks.
Special JS Feature
Yes, the test1
function uses a special JavaScript feature called the spread operator (...
). The spread operator was introduced in ECMAScript 2015 (ES6) and allows for concise object creation by expanding an array-like object into new objects. While widely supported, older browsers might not have this feature enabled.
Other Considerations
When creating objects with methods using these approaches:
test1
and test2
will produce similar performance results.test1
.Alternatives
Other alternatives to these approaches could include:
Object.create()
method to clone existing objects and add new properties.However, these alternatives might not be as straightforward or efficient as using a simple function like test1
or defining a class like test2
.