list = Array.from({
length: 1000
}, (v, i) => ({
id: 'id' + i
}));
obj = list.reduce((acc, cur) => {
acc[cur.id] = cur;
return acc;
}, {});
const list2 = list.map(item => item.id === 'id500' ? {item, updated: true} : item)
const obj2 = {obj, id500: {obj['id500'], updated: true}}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
update in array | |
update in obj |
Test name | Executions per second |
---|---|
update in array | 101810.4 Ops/sec |
update in obj | 1503.3 Ops/sec |
Let's dive into the provided benchmark code.
What is being tested?
The provided JSON represents a JavaScript microbenchmark that compares two approaches:
obj vs array again
).obj['id500']
) versus using the bracket notation with an object literal (i.e., obj.id500 = { ... }
).Options being compared:
Two approaches are compared:
list.map()
):const list2 = ...
).obj['id500']
) or bracket notation with an object literal (obj.id500 = { ... }
):obj
object identified by its key.Pros and cons:
list.map()
):obj['id500']
) or bracket notation with an object literal (obj.id500 = { ... }
):=
or a new object literal, which might add overhead.Library usage:
The provided benchmark code uses no external libraries. It relies solely on standard JavaScript features and syntax.
Special JS feature or syntax:
There are no special JS features or syntax used in this benchmark. However, it does utilize some advanced ES6 features like:
(v, i) => ({...})
){ ... }
)\r\n
)If you're not familiar with these features, don't worry – they are widely supported and commonly used in modern JavaScript development.
Alternative approaches:
For similar benchmarking or optimization purposes, you might want to explore other approaches:
forEach()
instead of map()
:Object.assign()
for updating objects:When working on microbenchmarks like this, consider the trade-offs between simplicity, readability, and performance when choosing your approach.