<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>
var a = ['hello', 'a', 'bc'];
function find(target, arr) {
for (let i = 0; i < arr.length; i++) {
if (target === arr[i]) return true;
}
return false;
}
var b = find('bc', a);
var a = ['hello', 'a', 'bc'];
var b = a.some(item => item === 'bc');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array for | |
array some |
Test name | Executions per second |
---|---|
array for | 113220272.0 Ops/sec |
array some | 153785904.0 Ops/sec |
Let's break down the provided benchmark and its test cases.
What is being tested?
The benchmark compares two ways to check if an element exists in an array: using the traditional concat()
method with a loop (also known as "array for") and the new ES6 spread operator (...
) with the some()
method.
Options compared
There are two options being compared:
some()
method, which returns a boolean value indicating whether at least one element in the array satisfies the provided condition.Pros and Cons
Array For:
Pros:
Cons:
concat()
Some Method:
Pros:
Cons:
Library: Lodash
The benchmark uses the Lodash library, which provides the some()
method. Lodash is a popular utility library that provides a set of functional programming helpers, including the some()
method.
Special JS feature or syntax
None mentioned in the provided code snippet. However, if we were to consider other test cases, we might see special features like:
However, this is not the case for the provided benchmark code.
Other alternatives
If you want to compare these two options in a more comprehensive way, you could also consider using other methods, such as:
indexOf()
or includes()
, which are built-in array methods that can be used to check if an element exists.For example, the test case for "array for" could use the following code:
var b = arr.indexOf('bc') !== -1;
Or the test case for "some method" could use the following code:
var b = [...arr].includes('bc');
These alternatives would require additional setup and configuration, but they provide more comprehensive comparisons of the performance characteristics of these two options.