var test = [1,2,3,4];
var c;
if (typeof test === 'object') { c++; }
if (Array.isArray(test)) { c++; }
if (test instanceof Array) { c++; }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
typeof | |
isArray | |
instanceof |
Test name | Executions per second |
---|---|
typeof | 13251956.0 Ops/sec |
isArray | 12989316.0 Ops/sec |
instanceof | 13220936.0 Ops/sec |
Let's break down the provided benchmark JSON and explain what's being tested.
Benchmark Definition
The benchmark is designed to compare three different approaches:
typeof
Array.isArray
instanceof
All three methods are used to check if a variable (test
) is an object or an array.
Pros and Cons of each approach:
typeof
: This method checks the type of a variable at runtime, using a special operator in JavaScript. It returns one of the following strings:"object"
for objects"number"
, "string"
, etc. for other numeric or string types"undefined"
for uninitialized variablesArray.isArray
: This method is specifically designed to check if an object is an array, using a static property on the Array
constructor.instanceof
: This method checks if an object is an instance of a particular constructor function. In this case, it's used to check if test
is an instance of the Array
constructor.typeof
and can handle arrays with non-numeric property names.Array
object.Library usage
None of the methods require any external libraries.
Special JavaScript feature or syntax
The benchmark uses a special feature of JavaScript called "strict equality" (===
), which is used to compare values without considering type conversions. This is not explicitly mentioned in the benchmark, but it's implied by using typeof
and instanceof
.
Other alternatives
There are other ways to check if an object or array in JavaScript:
test instanceof RegExp.test && test.value === undefined
constructor
property: test.constructor.name === 'Array'
new Array(test).length !== 0
However, these alternatives are not included in this benchmark.
Benchmark preparation code
The script preparation code creates an array test
and assigns it to the variable c
, which is then used as input for each test case. The var c;
statement at the end of the script preparation code creates a new variable c
, which is not referenced anywhere in the benchmark. This is likely done to ensure that the benchmark produces accurate results, even if the variable c
is not used elsewhere.
Individual test cases
Each test case uses one of the three approaches mentioned earlier:
typeof
: Checks if test
has an "object"
type.Array.isArray
: Checks if test
is a specific instance of the Array
constructor.instanceof
: Checks if test
is an instance of the Array
constructor.The benchmark result shows the execution time for each test case in different browsers, with typeof
performing slightly better than Array.isArray
and instanceof
.