<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
var primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,97]
_.includes(primes, 79)
primes.includes(79)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.includes | |
array.includes |
Test name | Executions per second |
---|---|
_.includes | 2192577.8 Ops/sec |
array.includes | 9388360.0 Ops/sec |
I'll break down the benchmark definition, test cases, and their results to explain what's being tested.
Benchmark Definition
The provided JSON represents a JavaScript microbenchmark that tests two different approaches for checking if an element exists in an array: using the _.includes
method from the Lodash library and the built-in array.includes
method.
Script Preparation Code
The script preparation code defines a constant primes
which is an array of prime numbers. This array will be used as the test data for both benchmarks.
Html Preparation Code
The HTML preparation code includes a reference to the Lodash JavaScript library, version 4.17.11, using a CDN. This library provides the _.includes
method that will be tested.
Test Cases
There are two individual test cases:
_.includes(primes, 79)
_.includes
primes.includes(79)
array.includes
Pros and Cons of Different Approaches
Library: Lodash
Lodash is a popular utility library for JavaScript that provides a wide range of functions, including _.includes
. It's designed to make common tasks easier and more efficient. In this benchmark, the _.includes
method is used to check if an element exists in the primes
array.
Special JS Feature/Syntax
There are no special JavaScript features or syntaxes mentioned in the provided code snippets. The tests only rely on standard JavaScript array methods.
Other Alternatives
If you're interested in exploring alternative approaches for checking if an element exists in an array, here are a few options:
Array.prototype.find()
and ===
:primes.includes(79) === primes.find((x) => x === 79);
forEach()
and checking the index:let found = false;
for (let i = 0; i < primes.length; i++) {
if (primes[i] === 79) {
found = true;
break;
}
}
primes.includes(79) === found;
Keep in mind that these alternatives may have different performance characteristics and are not as concise or readable as the original methods.