var arr = new Array(1000).fill(null);
for(let i = 0; i < arr.length; i++) {
if(i % 3 === 0) {
arr[i] = [1];
} else if(i % 2 === 0) {
arr[i] = {a: 1};
} else {
arr[i] = '1';
}
}
let circle = 5;
while(circle > 0) {
const check = arr.map(item => item instanceof Array);
circle--;
}
let circle = 5;
while(circle > 0) {
const check = arr.map(item => Array.isArray(item));
circle--;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
instanceof Array | |
Array.isArray() |
Test name | Executions per second |
---|---|
instanceof Array | 2815.7 Ops/sec |
Array.isArray() | 2878.6 Ops/sec |
I'd be happy to help explain the benchmark and its results.
Benchmark Definition
The benchmark is designed to compare two approaches for checking if an object is an array in JavaScript:
instanceof
operator (instanceof Array
)Array.isArray()
methodThe benchmark creation code creates a large array of 1000 elements, fills it with different types of values (null, arrays, objects, and strings), and then uses a while loop to iterate over the array.
Options Compared
The two options being compared are:
instanceof Array
: This operator checks if an object is a direct instance of the Array
class.Array.isArray()
: This method returns a boolean value indicating whether the given value is an array or not.Pros and Cons of Each Approach
instanceof
operator:Array
Array.isArray()
because it involves a type checkArray
Array.isArray()
method:instanceof
Library
There is no explicit library mentioned in the benchmark definition. However, the Array.isArray()
method is a built-in JavaScript method.
Special JS Feature or Syntax
The benchmark uses a feature called "array destructuring" (not explicitly used in this case, but implied by the use of arr.map()
) and also uses modern JavaScript syntax such as arrow functions (=>
), template literals (\r\n
), and the for...of
loop (not explicitly used in this case).
Other Considerations
The benchmark is designed to test the performance difference between these two approaches on a large array of mixed data types. The use of a while loop with a decreasing counter (circle--
) creates a microbenchmark that can be executed multiple times, allowing for accurate measurements.
Alternatives
If you were to create a similar benchmark, you could consider using other methods or libraries to check if an object is an array, such as:
typeof
operator to check the type of the object (typeof obj === 'object' && Array.isArray(obj)
)isArray()
functionKeep in mind that the best approach will depend on the specific use case and requirements of your project.