const obj = Object.create(null);
for (i = 0; i < 100_000; i++) {
obj[i] ??= i;
}
const obj = {};
for (i = 0; i < 100_000; i++) {
obj[i] ??= i;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.create(null); | |
{} |
Test name | Executions per second |
---|---|
Object.create(null); | 388.7 Ops/sec |
{} | 463.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
The provided benchmark measures the performance difference between two approaches:
Object.create(null)
: This method creates an object with no prototype chain, effectively making it a plain object without any inherited properties or methods.{}
(i.e., an object created using the literal syntax): This is another way to create a plain object in JavaScript.Both approaches are used to set up an object and then perform an assignment operation on its properties (obj[i] = i;
) 100,000 times. The difference lies in how the initial state of the object is created.
Now, let's discuss the pros and cons of each approach:
Object.create(null)
Pros:
Object.create(null)
object is generally faster than creating an empty object {}
because it avoids the overhead of parsing and constructing a new object literal.Cons:
Object.create()
can make code harder to read, especially for developers who are not familiar with this method.Object.create(null)
.An empty object {}
Pros:
{}
.Cons:
Object.create(null)
object due to parsing and construction overhead.Nullish coalescing assignment (??=
)
The benchmark also compares the performance of the nullish coalescing operator (??
) in combination with array indexing (obj[i] = i;
). This approach is often used for setting default values or initializations in JavaScript.
Pros:
obj[i] ??= i
is very concise and readable, making it an attractive choice for developers.??
).Cons:
Now, let's talk about libraries used in this benchmark. None of the provided test cases utilize any external libraries.
Regarding special JS features or syntax, there are a few to be aware of:
??
) was introduced in ECMAScript 2020 and supports most modern browsers.Object.create(null)
has been part of JavaScript since its inception but is still not widely used.If you're interested in exploring alternative benchmarking tools or techniques, consider the following options:
Keep in mind that benchmarking performance is often a complex task, involving various factors like cache efficiency, JIT optimization, and more.