<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.js"></script>
var strings = [
'one', 'two', 'three'
]
var regex = /^(one|two|three)$/;
var input = 'three'
// Native
!!strings.find(function (o) { return o == input; })
!!_.find(users, function (o) { return o==input; })
regex.test(input)
regex.test(input)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array find | |
_.find | |
regex | |
regex (i) |
Test name | Executions per second |
---|---|
array find | 7071586.0 Ops/sec |
_.find | 0.0 Ops/sec |
regex | 12618056.0 Ops/sec |
regex (i) | 12069677.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Overview
The benchmark compares the performance of three different approaches to check if an element exists in an array or string:
Array.prototype.find()
_.find()
function^
anchor with a regex pattern)Test Case 1: Array Find (Native)
!!strings.find(function (o) { return o == input; })
Array.prototype.find()
This test case uses the native JavaScript find()
method to search for an element in the strings
array. The callback function checks if the current element (o
) is equal to the input string.
Pros and Cons:
Pros:
Cons:
Array.prototype.find()
Test Case 2: _.find (Lodash)
!!_.find(users, function (o) { return o==input; })
_.find()
functionThis test case uses the Lodash find()
function to search for an element in the users
array. The callback function checks if the current element (o
) is equal to the input string.
Pros and Cons:
Pros:
find()
is not availableCons:
find()
Test Case 3: regex.test (Compiled)
^
anchor with a regex pattern)This test case uses a compiled regular expression to search for an element in the input string. The ^
anchor matches the start of the string, and the regex pattern is optimized for performance.
Pros and Cons:
Pros:
Cons:
Test Case 4: regex.test (Case-Insensitive)
^
anchor with a regex pattern)This test case uses the same compiled regular expression as the previous test case, but adds the (i)
flag to make the match case-insensitive.
Pros and Cons:
Pros:
Cons:
In summary, the benchmark compares the performance of three different approaches to check if an element exists in an array or string. The native JavaScript find()
method is generally the fastest but has limited support, while Lodash's _find()
function provides a fallback solution but adds memory overhead. The compiled regular expression approach offers fast execution time and minimal memory overhead, but may not work on older browsers or environments that don't support regular expressions.
Other alternatives to consider:
Array.prototype.some()
instead of find()
Sprintf
or String.prototype.includes()