var size = 10000;
var arr2 = [];
for (var i = 0; i < size; i++){
arr2.push(i);
}
arr2.length = 64;
var size = 10000;
var arr3 = [];
for (var i = 0; i < size; i++){
arr3.push(i);
}
arr3.splice(64);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set length to zero | |
Splice |
Test name | Executions per second |
---|---|
Set length to zero | 25226.4 Ops/sec |
Splice | 18901.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Overview
The provided benchmark tests two approaches to empty an array in JavaScript: setting the length to zero and using the splice
method with a negative index.
Options Compared
There are two main options being compared:
length
property of the array to zero, effectively clearing its contents.splice
with a negative index: This approach uses the splice
method with an index less than zero (in this case, -64) to remove elements from the end of the array.Pros and Cons
Pros:
Cons:
splice
with a Negative IndexPros:
Cons:
Library/Feature Considerations
Neither of these approaches relies on any specific libraries or advanced JavaScript features. However, some browsers may optimize or modify the execution behavior in certain situations (e.g., Safari's array optimization).
Other Alternatives
Besides setting the length to zero and using splice
with a negative index, other methods for emptying arrays include:
fill
method with an argument of zero: arr.fill(0)
new Array(size).fill().map((_, i) => null)
(a more complex approach)empty
functionIt's worth noting that some browsers may have additional methods or optimizations for emptying arrays, such as arr.set(0, 0)
on Safari.
In summary, setting the length to zero is generally the fastest and most straightforward way to empty an array in JavaScript, but using splice
with a negative index can be useful when working with certain array implementations or requirements.