var test = [1,2,3,4];
var c;
if (test instanceof Array) { c++; }
if (Array.isArray(test)) { c++; }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
if (test instanceof Array) { c++; } | |
if (Array.isArray(test)) { c++; } |
Test name | Executions per second |
---|---|
if (test instanceof Array) { c++; } | 3092570.8 Ops/sec |
if (Array.isArray(test)) { c++; } | 3119061.2 Ops/sec |
Let's break down the provided benchmark definition and test cases to understand what is being tested.
Benchmark Definition
The benchmark definition is a JSON object that contains the script preparation code, HTML preparation code (which is null in this case), and a brief description of the benchmark. In this case, the script preparation code simply declares an array test
with some values. The HTML preparation code is not used for this specific benchmark.
Test Cases
There are two test cases:
if (test instanceof Array) { c++; }
This test case checks if the value of c++
, which increments a variable c
, returns an Array
. The JavaScript syntax instanceof
is used to check if an object is an instance of a particular constructor.
if (Array.isArray(test)) { c++; }
This test case checks if the value of c++
returns true when passed to the Array.isArray()
function, which returns true
if the input is an array-like object or null.
Comparison
The two test cases are comparing the behavior of JavaScript's built-in functions instanceof
and Array.isArray()
. The main difference between these two checks lies in their behavior for non-array-like objects.
instanceof
will return false even if the value is an array-like object, whereas Array.isArray()
will return true.Array.isArray()
is more permissive but may perform additional work to check if the input has the properties of an array. On the other hand, instanceof
returns immediately without checking for these properties.Pros and Cons
instanceof
:Array.isArray()
:Other Considerations
Array.isArray()
is generally considered more accurate and safe to use than instanceof
for checking if a value is an array-like object.instanceof
and Array.isArray()
may depend on the specific requirements of the test case.Library
In this benchmark, there are no external libraries being used. All code is contained within the script preparation code provided in the benchmark definition.
Special JS Features or Syntax
None mentioned.
Alternatives
There are other ways to check if a value is an array-like object:
typeof
operator with equality checks (if (typeof test === 'object' && !Array.isArray(test) && typeof c++ !== 'undefined')
)if (Object.prototype.hasOwnProperty.call(test, 'length'))
)isArrayLike()
functionKeep in mind that these alternatives may not be as straightforward or efficient as using Array.isArray()
.