var types = {
array: [1,2,3],
number: 123,
string: '123',
map: new Map([[1,1],[2,2],[3,3]]),
set: new Set([1,2,3]),
buffer: new ArrayBuffer([1,2,3]),
boolean: true,
arrow: () => {},
function: function () {},
object: {},
u8: new Uint8Array(),
u16: new Uint16Array(),
u32: new Uint32Array(),
i8: new Int8Array(),
i16: new Int16Array(),
i32: new Int32Array()
}
var keys = Object.keys(types)
keys.map(key => Array.isArray(types[key]) === true)
keys.map(key => (types[key] instanceof Array) === true)
keys.map(key => types[key][Symbol.iterator] !== undefined)
keys.map(key => Object.prototype.toString.call(types[key]).slice(8, -1) == 'Array')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
isArray | |
instanceof | |
Symbol.iterator | |
Object.prototype.toString.call |
Test name | Executions per second |
---|---|
isArray | 145145.9 Ops/sec |
instanceof | 139957.8 Ops/sec |
Symbol.iterator | 87368.4 Ops/sec |
Object.prototype.toString.call | 94209.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Overview
The provided JSON represents a benchmark test on MeasureThat.net
that compares four different approaches to check if a value is an array in JavaScript:
Array.isArray()
instanceof Array
Symbol.iterator
(also checks for TypedArray, Map, and Set)Object.prototype.toString.call()
with a slice manipulationOptions Compared
Each option is compared using the following test cases:
keys.map(key => ... === true)
to check if the condition returns true
in each caseHere's a brief explanation of each option:
Array.isArray()
: This method takes an array-like object (such as a TypedArray, Map, or Set) and returns true
if it is an actual array.Array
constructor function.Symbol.iterator
: In JavaScript, arrays have a Symbol.iterator
property that returns an iterator object. Checking for this property (or its presence) can help identify whether a value is an array-like object.Object.prototype.toString.call()
with slice manipulation: This method uses the toString()
method of the prototype chain to get a string representation of the object, and then uses slicing (slice(8, -1)
) to extract the type of the object from the string.Pros and Cons
Here's a brief summary of each option:
Array.isArray()
:false
for TypedArrays or other array-like objects that don't have an array
property.Array.isArray()
for checking if a value is actually an array.true
for any object that is a subclass of Array
, which might not be desirable.Symbol.iterator
:false
if the value doesn't have an iterator symbol (although this is rare).Object.prototype.toString.call()
with slice manipulation:Array.isArray()
.