var obj = {}
for (const key of 'abcdefghijklmnopqrstuvwxyz'.split())
obj[key] = Math.random()
Object.keys(obj).map((key) => [key, obj[key]])
Object.entries(obj).map(([key, value]) => [key, value])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.keys with obj[key] | |
Object.entries |
Test name | Executions per second |
---|---|
Object.keys with obj[key] | 15630284.0 Ops/sec |
Object.entries | 9898636.0 Ops/sec |
I'd be happy to explain the benchmark and its findings.
What is being tested?
The provided benchmark measures the performance of two different approaches for iterating over an object in JavaScript: Object.keys
with the "with obj[key]" syntax, and Object.entries
. The test creates a large object obj
with random key-value pairs using the script preparation code, and then uses both Object.keys
and Object.entries
to map each key-value pair.
Options compared
There are two options being compared:
Pros and cons
Library and purpose
In this benchmark, there is no external library used. The Object.keys
and Object.entries
methods are built-in JavaScript functions that operate on objects.
Special JS feature or syntax
There is no special JavaScript feature or syntax being tested in this benchmark. It only relies on standard JavaScript functionality.
Benchmark preparation code and result
The script preparation code creates a large object obj
with random key-value pairs using the for...of
loop, which is a modern JavaScript feature that allows iterating over iterable objects like strings. The HTML preparation code is empty.
The benchmark results show the execution per second for each test case on a specific browser and device platform: Firefox 120 on a Macintosh (Intel Mac OS X 10.15).
Other alternatives
If you're interested in exploring alternative approaches, here are some options:
for...in
loop: This approach iterates over the object's own enumerable properties, which may include inherited properties.map()
function with a custom callback: This approach can be more flexible since it allows using a custom callback function to transform each key-value pair.Keep in mind that these alternatives may change the behavior of the benchmark significantly, so it's essential to consider the specific requirements and constraints of your use case when choosing an approach.