How to Accurately Validate an Array

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.

Note

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.

Performance Check of Array Validation Method in Deno

Performance Check of Array Validation Method in Edge

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.

first commit : 09/05/24
last commit : 09/08/24
Made By Svelte Rune, Designed By chimi
last commit : 10/17/24 comment : :memo: 문장 레벨 변경