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;
c += Number(a instanceof Array);
c += (0 + (a instanceof Array));
if(Array.isArray(a)) ++c;
c += Number(Array.isArray(a))
c += (0 + (Array.isArray(a)));
if(a.length > -1) ++c;
c += Number(a.length > -1);
c += (0 + (a.length > -1));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Instanceof if | |
Instanceof npe | |
Instanceof mpe | |
isArray if | |
isArray npe | |
isArray mpe | |
Length if | |
Length npe | |
Length mpe |
Test name | Executions per second |
---|---|
Instanceof if | 727988.6 Ops/sec |
Instanceof npe | 466704.2 Ops/sec |
Instanceof mpe | 712120.8 Ops/sec |
isArray if | 670750.4 Ops/sec |
isArray npe | 545159.4 Ops/sec |
isArray mpe | 613199.4 Ops/sec |
Length if | 1166748.8 Ops/sec |
Length npe | 730092.0 Ops/sec |
Length mpe | 1191733.0 Ops/sec |
Benchmark Overview
The provided JSON represents a JavaScript microbenchmarking test case on the MeasureThat.net website. The benchmark compares different ways of checking if an array is valid or not using the Array.isArray()
method and the instanceof
operator.
Options Compared
a instanceof Array
to a number (0 or 1) before adding it to c
. The idea is that instanceof
will return true for arrays, but not for non-array values, so this conversion allows for easy addition.(a instanceof Array)
in parentheses before adding it to c
. The idea is that this prevents short-circuit evaluation and ensures that the check is always performed regardless of the value of a
.a
is an array, incrementing c
only if it is.a
is greater than -1. Since arrays always have a valid length (or -1 for empty arrays), this effectively checks if a
is an array.Pros and Cons
instanceof
will always return true for arrays, which can lead to false positives.instanceof
will always return true for arrays.a
; Cons: slightly more complex, may be slower due to the additional operation.Library Usage
The Array.isArray()
method is a built-in JavaScript method that checks if an object is an array. It is used in several test cases to check if a
is an array.
Special JS Features/Syntax
None mentioned in the provided benchmark definition. However, it's worth noting that some older browsers may not support instanceof
or Array.isArray()
for certain types of objects (e.g., arrays of custom objects).
Benchmark Results
The benchmark results show that:
Array.isArray()
method.instanceof
options but can produce false negatives.Overall, the choice of which option to use depends on performance requirements and potential sources of error.