<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
var arr = [];
for(var i = 0; i < 5000; i++){
arr.push({value:getRandomInt(100)});
}
var obj = {};
var str = "hello world";
_.isArray(arr)
_.isArray(obj)
_.isArray(str)
Array.isArray(arr)
Array.isArray(obj)
Array.isArray(str)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash | |
native |
Test name | Executions per second |
---|---|
lodash | 154111776.0 Ops/sec |
native | 170240864.0 Ops/sec |
I'll break down the benchmark and its components, explaining what's being tested, compared, and their pros and cons.
Benchmark Overview
The benchmark measures the performance of two approaches to check if an object is an array:
Array.isArray()
method: Using the built-in Array.isArray()
function._.isArray()
function: Using a utility function from the Lodash library, specifically _.isArray()
, which provides a wrapper around the native implementation.Script Preparation Code
The script preparation code creates an array of 5,000 objects with random values and two empty objects (arr
and obj
). It also defines a string variable (str
). This setup is intended to simulate a real-world scenario where these checks might be used.
Html Preparation Code
The HTML preparation code includes the Lodash library (version 4.17.5) via a CDN link, which makes its functions available for use in the script.
Individual Test Cases
There are two test cases:
_.isArray()
function: This test case uses the _.isArray()
function from Lodash to check if arr
, obj
, and str
are arrays.Array.isArray()
method: This test case uses the built-in Array.isArray()
function to perform the same checks.Pros and Cons of Each Approach
_.isArray()
function:Array.isArray()
method:Array.isArray()
).Library and Purpose
Lodash is a utility library for JavaScript that provides a collection of functional programming helpers. In this case, the _isArray()
function from Lodash is used to check if an object is an array.
Special JS Features or Syntax
There are no special features or syntax mentioned in the benchmark setup that would affect its performance comparison. The focus is on comparing the performance of two approaches to checking array-like objects.
Other Alternatives
If you want to use other libraries or implementations for checking if an object is an array, consider:
_isArray()
function.Array.isArray()``**: If the target environment supports ES6 features, using the built-in
Array.isArray()` function can be a good option.Keep in mind that these alternatives might introduce different dependencies or behaviors compared to Lodash and the native JavaScript implementation.