var c = 0, a = Array(10).fill().map((el,i) => i);var c = 0, a = Array(10).fill().map((el,i) => i);
if(a instanceof Array) ++c;
if(Array.isArray(a)) ++c;
if(a.length > -1) ++c;
if(a.length !== undefined) ++c;
if(a.map) ++c;
if(a.constructor === Array) ++c;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Instanceof if | |
isArray if | |
Length if | |
Length if undef | |
Map if | |
Ctor check |
Test name | Executions per second |
---|---|
Instanceof if | 5494472.0 Ops/sec |
isArray if | 5395938.0 Ops/sec |
Length if | 8324989.5 Ops/sec |
Length if undef | 5432592.0 Ops/sec |
Map if | 8486778.0 Ops/sec |
Ctor check | 5373641.0 Ops/sec |
Overview
MeasureThat.net is a platform that allows users to create and run JavaScript microbenchmarks. The provided benchmark definition json represents the test case, which compares various approaches for checking if an array-like object is actually an array.
Benchmark Definition
The benchmark definition json has three main sections:
a
using the Array(10).fill().map((el,i) => i)
method, which creates a new array with 10 elements that increment by index.if(a instanceof Array) ++c;
if(Array.isArray(a)) ++c;
if(a.length > -1) ++c;
if(a.length !== undefined) ++c;
if(a.map) ++c;
if(a.constructor === Array) ++c;
Each test case is a simple if-statement that checks the condition and increments a counter variable c
if true.
Options Compared
The benchmark compares six different approaches to check if an array-like object is actually an array:
instanceof
: Checks if the object is an instance of the Array constructor.Array.isArray()
: A method provided by the Array prototype that checks if an object is an array.map()
method is defined on the object, which is another common way to check if an object is an array-like object.Pros and Cons
Here's a brief pros and cons summary for each approach:
instanceof
:Array.from()
).Array.isArray()
:map()
method is defined but returns a non-array value).Other Considerations
The benchmark also considers various factors such as:
These factors can affect the results and provide a more accurate representation of real-world performance characteristics.
Alternatives
Some alternative approaches to checking if an array-like object is actually an array include:
Object.is(a, Array)
(if supported by the browser)isArrayLike()
functionHowever, these alternatives may not be as widely supported or perform as well as the approaches compared in this benchmark.