var size = 10000;
var arr1 = [];
for (var i = 0; i < size; i++){
arr1.push(i);
}
arr1 = [];
var size = 10000;
var arr2 = [];
for (var i = 0; i < size; i++){
arr2.push(i);
}
arr2.length = 0;
var size = 10000;
var arr3 = [];
for (var i = 0; i < size; i++){
arr3.push(i);
}
arr3.splice(0, arr3.length);
var size = 10000;
var 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 | 49391.8 Ops/sec |
Set length to zero | 49103.2 Ops/sec |
Splice | 47280.0 Ops/sec |
Pop all values | 27019.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
What is tested?
The provided benchmark tests four different approaches to empty an array in JavaScript:
arr1 = []
).arr2.length = 0
).splice(0, arr3.length)
method to remove all elements from an array (arr3.splice(0, arr3.length)
).while(arr4.length > 0){ arr4.pop();}
).Options comparison
Here's a brief overview of each approach and its pros and cons:
arr1
. However, it requires more memory allocation compared to other methods.splice(0, arr3.length)
removes all elements from the array by updating the internal length property. This method is similar to setting the length to zero but uses a different API. It can be slower than instantiating a new array because it needs to perform additional operations on the array object.pop()
method and discarding the returned value.Library usage
None of the provided benchmark definitions uses any external libraries or frameworks.
Special JS feature or syntax
There are no special JavaScript features or syntax used in these benchmark definitions. The code is written in plain JavaScript and follows standard syntax and semantics.
Other alternatives
If you're interested in exploring alternative approaches to emptying an array, here are a few more options:
fill()
method: arr5.fill(0);
would clear the array by filling it with zeros.map()
method with an identity function: arr6.map(() => 0);
would create a new array with all elements set to zero and then discard the original array.reduce()
method with an identity function: arr7.reduce((a, b) => a + b, 0);
would create a new array with the sum of all elements and then discard the original array.Keep in mind that these alternatives may have different performance characteristics compared to the original benchmark definitions.