<script src='https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js'></script>
var a = []
for(var i=0; i<100; i++){
a[i] = `val${i}`
}
_.isArray(a);
Array.isArray(a)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_ | |
nat |
Test name | Executions per second |
---|---|
_ | 2089063.4 Ops/sec |
nat | 1823651.6 Ops/sec |
I'll break down the benchmark and explain what's being tested, compared options, pros and cons of those approaches, library usage, special JavaScript features or syntax, and other considerations.
Benchmark Overview
The benchmark tests two alternatives for checking if an array is an instance of the Array
constructor:
_
(the underscore function) from the Underscore.js libraryArray.isArray()
(a built-in JavaScript method)Script Preparation Code
The script preparation code creates a large array a
with 100 elements, each containing a string value "val${i}"
, where i
is an index.
var a = [];
for (var i = 0; i < 100; i++) {
a[i] = 'val' + i;
}
Html Preparation Code
The HTML preparation code includes a reference to the Underscore.js library, which provides the _
function used in the benchmark.
<script src='https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js'></script>
Test Cases
There are two test cases:
_.isArray(a);
Array.isArray(a);
Both test cases create an array a
and pass it to the respective function.
Library Usage - Underscore.js
Underscore.js is a popular JavaScript utility library that provides a concise way to perform common tasks, such as iterating over arrays or strings, creating functions, and more. The _
function in this benchmark is used to check if an array is an instance of the Array
constructor.
Comparison Options
The two options being compared are:
_.isArray(a);
Array.isArray(a);
Pros and Cons of Each Approach:
_ (Underscore.js)
Pros:
Array.isArray()
because it can use native JavaScript methods under the hood.Cons:
Array.isArray()
method.Array.isArray()
Pros:
Cons:
_.isArray()
if optimized native methods are used under the hood.Other Considerations
Array.isArray()
, while another instance runs faster with _.isArray(a);
.Alternatives
If you don't want to use a third-party library like Underscore.js, you can implement an array check function similar to Array.isArray()
using native JavaScript methods. For example:
function isArray(arr) {
return arr instanceof Array && arr.constructor === Array;
}
Alternatively, you could explore other libraries or implementations that provide alternative array check functions.
Keep in mind that the choice of implementation ultimately depends on your specific use case and performance requirements.