for (var e = 0; e < 100000; e++){
let size = 100;
let arr1 = [];
for (var i = 0; i < size; i++){
arr1.push(i);
}
arr1 = [];
}
for (var e = 0; e < 100000; e++){
let size = 100;
let arr2 = [];
for (var i = 0; i < size; i++){
arr2.push(i);
}
arr2.length = 0;
}
for (var e = 0; e < 100000; e++){
let size = 100;
let arr3 = [];
for (var i = 0; i < size; i++){
arr3.push(i);
}
arr3.splice(0, arr3.length);
}
for (var e = 0; e < 100000; e++){
let size = 100;
let arr4 = [];
for (var i = 0; i < size; i++){
arr4.push(i);
}
while(arr4.length > 0){
arr4.pop();
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Just instantiate new array | |
Set length to zero | |
Splice | |
Pop all values |
Test name | Executions per second |
---|---|
Just instantiate new array | 13.5 Ops/sec |
Set length to zero | 10.3 Ops/sec |
Splice | 11.6 Ops/sec |
Pop all values | 9.1 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Description The benchmark is designed to measure the performance of three different approaches for emptying an array in JavaScript:
let arr = []
)arr.length = 0
)splice(0, arr.length)
to remove all elements from an arraywhile(arr.length > 0) { arr.pop(); }
)Options Comparison
The benchmark compares the performance of these four approaches on a large array of size 100,000 elements.
Library Usage None of the benchmark definitions use any external libraries or frameworks. The focus is solely on measuring the performance of built-in JavaScript features.
Special JS Features/Syntax
The benchmark definition splice(0, arr.length)
uses the splice()
method with two arguments: the starting index (0) and the number of elements to remove (arr.length
). This syntax is a shorthand way to remove all elements from an array.
Other Alternatives
If you want to test alternative approaches for emptying an array in JavaScript, some other options include:
Array.prototype.fill(0)
or Array.from(new Array(size).fill(0))
to create a new array with all elements set to 0.let arr = new Int32Array(size);
and then setting all elements to 0 using arr.fill(0)
.Keep in mind that these alternatives may have different performance characteristics depending on the specific use case and browser version.