var items = Array.from(Array(1000), (_,x) => ({key: x, value: x*10}));
var objContainer = {};
var arrContainer = [];
for (let i = 100; i >= 0; i--) {
const index = Math.floor(Math.random() * 1000);
const item = items[index];
objContainer[item.key] = item;
arrContainer.push(item)
}
items.forEach(item => objContainer[item.value])
items.forEach(item => arrContainer.find(containerItem => containerItem.value === item.value))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object access | |
Array find |
Test name | Executions per second |
---|---|
Object access | 1308662.6 Ops/sec |
Array find | 1886.0 Ops/sec |
This benchmark compares two ways to find an object within a collection: accessing it directly through an object key and using the find
method on an array.
Object Access:
items.forEach(item => objContainer[item.value])
item.value
as a key to access and potentially modify an object (objContainer
).Array Find:
items.forEach(item => arrContainer.find(containerItem => containerItem.value === item.value))
find
method on the arrContainer
array to locate an object whose value
property matches the current item's value
.Pros and Cons:
Approach | Pros | Cons |
---|---|---|
Object Access | Potentially faster for retrieving a specific value if you know the key in advance. | Requires knowing the object's key structure beforehand. Less flexible than array-based searching. |
Array Find | More flexible, can search based on any property. Can handle dynamic data structures more easily. | Potentially slower than direct object access for frequent lookups using known keys. |
Other Considerations:
find
offers more flexibility.find
might be a better choice.Alternatives:
Besides these two methods, consider:
find
implementations that might be faster than the built-in array method.Let me know if you have any other questions!