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);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set length to zero | |
Splice |
Test name | Executions per second |
---|---|
Set length to zero | 18615.0 Ops/sec |
Splice | 20219.7 Ops/sec |
Let's break down the JavaScript microbenchmark on MeasureThat.net.
Benchmark Definition
The benchmark is designed to compare two approaches for emptying an array in JavaScript: setting the length
property of the array to 0, and using the splice()
method with its first argument set to 0 and the second argument equal to the length of the array.
Options Compared
length
property of the array to 0, effectively emptying it.splice()
method with its first argument set to 0 (the index of the first element) and the second argument set to the length of the array, which removes all elements from the start of the array.Pros and Cons
Array.prototype.slice()
).Library Usage
There is no explicit library usage in this benchmark. However, it's worth noting that some JavaScript engines (e.g., SpiderMonkey) have internal optimizations for certain operations, which may affect the benchmark results.
Special JS Features or Syntax
None are explicitly mentioned in the benchmark definition or individual test cases.
Other Alternatives
In addition to setting the length
property and using splice()
, other approaches to emptying an array include:
Array.prototype.length = 0;
arr = new Array(size).fill(0);
(a more efficient approach that creates a new array with the desired length)arr = arr.map((_, i) => { arr[i] = undefined; return i; });
(a more explicit approach using a map function)Keep in mind that these alternatives may have varying levels of performance, compatibility, and code readability.
I hope this explanation helps!