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.
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.
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');
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.
Array.isArray
Faster?The reason is that Array.isArray
is optimized internally.
instanceof
Slower?instanceof
checks the prototype chain of the object.
In other words, it validates from the parent to the ancestor.
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.