<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>
var a = [{item:'hello'}, {item:'a'}, {item:'bc'}];
var b = a.find(item => item.item === 'bc');
var a = [{item:'hello'}, {item:'a'}, {item:'bc'}];
var b = _.find(a, item => item.item === 'bc');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array find | |
_.find |
Test name | Executions per second |
---|---|
array find | 41748360.0 Ops/sec |
_.find | 3809075.0 Ops/sec |
Let's break down what is being tested in this benchmark and compare the two approaches.
Benchmark Context
The benchmark compares the performance of two ways to find an element in an array:
...
), which returns a new array with the specified item.concat()
method, which concatenates a new array with the existing array.Options Compared
...
): Returns a new array with the specified item.concat()
Method: Concatenates a new array with the existing array.Comparison
In the benchmark, two test cases are used to compare the performance of these two approaches:
find
with an arrow function (item => item.item === 'bc'
)_
.find` from the Lodash library with a similar arrow functionThe _.find
approach is used as a control group, allowing us to isolate the performance impact of using the spread operator.
Library
In this benchmark, the Lodash library is used for the _
.findtest case. Lodash provides various utility functions for working with arrays and objects, including
find`, which finds the first element in an array that satisfies a predicate function.
Special JS Feature/Syntax
The new ES6 spread operator (...
) is used in the benchmark. This feature allows creating a new array by spreading elements from an existing array or object into a new array. In this case, it's used to create a new array with the specified item, which is then searched for.
Alternatives
Other alternatives to using the spread operator and concat()
method include:
Array.prototype.indexOf()
or Array.prototype.findIndex()
, which return the index of the first occurrence of the specified element.Array.prototype.map()
with a callback function that returns a new array with the desired elements.These alternatives may have different performance characteristics depending on the specific use case and requirements.