var {toString} = Object.prototype;
var arr = [1, 2, 3, 4];
var c =0;
if(toString.call(arr) === '[object Array]') {c++}
if(arr instanceof Array) {c++}
if(Array.isArray(arr)) {c++}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
toString | |
instanceof | |
isArray |
Test name | Executions per second |
---|---|
toString | 84956104.0 Ops/sec |
instanceof | 370184256.0 Ops/sec |
isArray | 127403720.0 Ops/sec |
I'd be happy to help you understand the JavaScript benchmark on MeasureThat.net.
Benchmark Overview
The benchmark measures the performance difference between three ways to check if an array is an array in JavaScript: using toString.call(arr) === '[object Array]'
, arr instanceof Array
, and Array.isArray(arr)
.
Options Compared
The three options being compared are:
toString()
function to convert the array to a string, and then compares it to the string representation of [object Array]
. This is a low-level approach that checks if the array's prototype chain contains the Array
object.instanceof
operator to check if an instance of Array
can be returned by calling constructor()
on arr
. This method is more intuitive and straightforward, but might have performance implications depending on the array's prototype chain.Array
function to check if an object passes the Array constructor test suite. This method is often used in modern JavaScript code, but might be less well-known.Pros and Cons of Each Approach
instanceof
for objects.Library and Special JS Features
The benchmark uses none of any library or special JavaScript feature beyond the standard ECMAScript features.
Other Considerations
When choosing between these approaches, consider the following factors:
toString.call(arr) === '[object Array]'
might be a good choice. However, this approach may have implications for arrays with custom prototypes.arr instanceof Array
or Array.isArray(arr)
might be a better choice due to their more intuitive nature.Array.isArray(arr)
is a good option.Alternatives
If these three approaches are not sufficient for your needs, consider using other methods:
Object.getPrototypeOf()
: This method can be used to check if an object's prototype chain contains the Array
object.Array.prototype.forEach()
: This method can be used to test whether a function takes at least two arguments.Array.prototype.every()
: This method can be used to test whether every element in an array passes a certain condition.Keep in mind that these alternatives might have different performance implications or trade-offs depending on the specific use case.