var test = [1,2,3,4];
var c;
if (test instanceof Array) { c++; }
if (Array.isArray(test)) { c++; }
if (test.constructor === Array) { c++; }
if (test.constructor.name === 'Array') { c++; }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Instanceof | |
isArray | |
variable.constructor | |
variable.constructor name |
Test name | Executions per second |
---|---|
Instanceof | 5021448.5 Ops/sec |
isArray | 5174942.5 Ops/sec |
variable.constructor | 5276821.5 Ops/sec |
variable.constructor name | 4160858.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and the pros/cons of each approach.
Benchmark Overview
The website MeasureThat.net
allows users to create and run JavaScript microbenchmarks. The current benchmark is testing four different approaches to check if a variable is an array:
instanceof Array
Array.isArray(test)
test.constructor === Array
test.constructor.name === 'Array'
Approach 1: instanceof Array
This approach uses the instanceof
operator, which checks if an object is a constructor of another object.
Pros:
Cons:
instanceof
operatorObject.create()
or Set.prototype.from()
)Approach 2: Array.isArray(test)
This approach uses a built-in method on the Array
constructor, which checks if an object is an array.
Pros:
Cons:
Object.create()
or Set.prototype.from()
)Approach 3: test.constructor === Array
This approach checks the constructor property of a variable and compares it to the Array
constructor.
Pros:
Cons:
Object.create()
or Set.prototype.from()
)Array
prototypeApproach 4: test.constructor.name === 'Array'
This approach uses the name
property of a constructor to check if it's an array.
Pros:
Cons:
name
property (introduced in ECMAScript 2015)Library:
In this benchmark, no libraries are used. However, if a library were required, some alternatives could be considered:
isArray()
function that can be used as an alternative to Array.isArray()
.isArray()
matcher that can be used for similar purposes.Special JS Features/Syntax:
The benchmark does not use any special JavaScript features or syntax, such as async/await, ES6 classes, or TypeScript.
Other Alternatives:
If you needed to compare these approaches in a different context, some alternative methods could be considered:
In summary, each approach has its pros and cons, and the choice of method depends on the specific requirements and constraints of your project.