var obj = (new Array(1000)).fill(null).reduce((prev, newVal) => {prev[Math.random() + ''] = Math.random() + ''; return prev; }, { sausage: 'tst' });
var array = Object.keys(obj);
array.find((item) => item === 'sausage')
obj['sausage']
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
find | |
Object[key] |
Test name | Executions per second |
---|---|
find | 1050238528.0 Ops/sec |
Object[key] | 1577858304.0 Ops/sec |
I'd be happy to explain the JavaScript microbenchmark on MeasureThat.net.
Benchmark Overview
The benchmark compares the performance of two approaches: using the array.find()
method and accessing an object key directly (i.e., obj['sausage']
).
Approaches Compared
array.find()
method is used to search for a specific element in an array. In this case, it's searching for an element that matches the string 'sausage'
.obj['sausage']
.Pros and Cons
obj['sausage']
syntax.Library Used
None mentioned in this specific benchmark. However, it's worth noting that libraries like Lodash (which provides find()
functionality) might affect the results.
Special JS Features/Syntax
There are no special JavaScript features or syntax used in this benchmark.
Other Alternatives
For searching arrays, other approaches could be:
indexOf()
: A method that returns the index of the first occurrence of a specified value.some()
or every()
.For accessing object properties, alternative syntaxes might include:
obj['sausage'].prop
).getProp(obj, 'sausage')
).Keep in mind that these alternatives may not be optimized for performance by JavaScript engines and should be considered when choosing the best approach for your specific use case.
Benchmark Results
The latest benchmark results show that:
array.find()
method is faster (executions per second: 16504123.0) compared to accessing an object key directly (executions per second: 15637711.0).These results suggest that the array.find()
method is optimized for performance in this specific use case. However, it's essential to consider other factors, such as readability and maintainability, when choosing between these approaches in your own code.