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()
}
const t1 = types.array instanceof Array
const t2 = types.object instanceof Array
const t1 = Array.isArray(types.array)
const t2 = Array.isArray(types.object)
const t1 = types.array[Symbol.iterator] !== undefined
const t2 = types.object[Symbol.iterator] !== undefined
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
instanceof | |
isArray | |
Symbol.iterator |
Test name | Executions per second |
---|---|
instanceof | 78289448.0 Ops/sec |
isArray | 77950024.0 Ops/sec |
Symbol.iterator | 53720636.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares different ways to check if an object is an array or not in JavaScript. The test cases cover three approaches:
instanceof
isArray
Symbol.iterator
These methods are used to determine if a value is an array, and the benchmark measures their performance.
Options Compared
The benchmark compares the following options:
instanceof Array
: This method checks if the object's prototype chain includes the Array
constructor.Array.isArray()
: This method takes an object as an argument and returns a boolean indicating whether the object is an array or not.Symbol.iterator
property: In JavaScript, arrays have a Symbol.iterator
property that can be used to iterate over the elements of an array.Pros and Cons
Here's a brief summary of each approach:
instanceof Array
:Array.isArray()
: Object.values()
returns an array-like object).Symbol.iterator
:instanceof
or Array.isArray()
for large arrays, as it only checks for the presence of the property.Object()
) and requires additional processing to iterate over the elements.Library Usage
There is no explicit library usage in this benchmark. However, it's worth noting that Array.isArray()
is a built-in method in JavaScript.
Special JS Features or Syntax
This benchmark does not use any special JavaScript features or syntax beyond what's commonly used in modern JavaScript development.
Alternative Approaches
Other ways to check if an object is an array include:
typeof
operator with the array
keyword: typeof obj === 'object' && obj instanceof Array
Object.keys(obj).length > 0
)Keep in mind that these approaches may have different performance characteristics and may not be as efficient as using built-in methods like Array.isArray()
.
Overall, the benchmark provides valuable insights into the performance of different approaches to checking if an object is an array in JavaScript.