There was a need for a deep copy of an object.
Since I am not using any libraries, I am implementing it myself. 🤣
Among the methods to accurately check an array, let's explore whether instanceof
or Array.isArray
is the wiser choice.
Array.isArray
was introduced in ES5.
Conclusion: Which Should You Use?
If instanceof Array
yields different results, it is likely due to code designed within an iframe. If code consistency is a priority, you can use instanceof Array
.
However, if you are using iframe
, you should opt for Array.isArray
.
I conducted extensive tests to find significant performance differences, but in actual usage environments, no meaningful differences were observed.
Performance Test
I conducted a performance test validating an empty array ten billion times in both Edge and Deno.
/** @type {Array<Array<number>>} */
const arr = [];
const time = 10_000_000_000;
// 1st
console.time('Array.isArray');
for (let i = 0; i < time; i++) {
Array.isArray(arr);
}
console.timeEnd('Array.isArray');
// 2nd
console.time('instanceof');
for (let i = 0; i < time; i++) {
arr instanceof Array;
}
console.timeEnd('instanceof');
Array.polyfillIsArray = function (obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
// 3rd
console.time('Array.polyfillIsArray');
for (let i = 0; i < time; i++) {
Array.polyfillIsArray(arr);
}
console.timeEnd('Array.polyfillIsArray');
Results
The lower the number, the better the performance.
To achieve meaningful results, I ran the tests ten billion times, and Array.isArray
emerged as the fastest.
Why is Array.isArray
Faster?
The reason is that Array.isArray
is optimized internally.
Why is instanceof
Slower?
instanceof
checks the prototype chain of the object.
In other words, it validates from the parent to the ancestor.
Why is Array.polyfillIsArray
Slower?
Array.polyfillIsArray
is slower because this method calls the Object.prototype.toString
method and goes through the process of checking the resulting string.
This process requires more operations than the built-in function Array.isArray
, making it relatively slower.