var array = [];
for(var i = 0; i < 1000000; i++){array.push(Math.random());}
while (array.length > 0)
{
array.pop();
}
while (array.length > 0)
{
array.shift();
}
array.length = 0
array = []
array.splice(0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
pop | |
shift | |
length | |
reassignment | |
.splice(0) |
Test name | Executions per second |
---|---|
pop | 10565134.0 Ops/sec |
shift | 10082531.0 Ops/sec |
length | 7021170.5 Ops/sec |
reassignment | 7890180.0 Ops/sec |
.splice(0) | 8190911.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The benchmark definition provided represents a basic JavaScript function that creates an array, populates it with random numbers, and then performs various operations on the array. The specific operation being tested is whether to clear the entire array using one of the following methods:
array.length = 0
array = []
The benchmark also includes four different ways to remove elements from the array:
while (array.length > 0) { array.pop(); }
- Removes elements from the end of the array.while (array.length > 0) { array.shift(); }
- Removes elements from the beginning of the array..splice(0)
- Removes the first element from the array using the splice()
method.Options Compared
The benchmark compares four different approaches to clear and manipulate the array:
array.length = 0
: Sets the length property of the array to 0, effectively clearing the array.array = []
: Reassigns the entire array to an empty array, clearing its contents..splice(0)
: Uses the splice()
method with a starting index of 0 to remove the first element from the array.while (array.length > 0) { array.pop(); }
and while (array.length > 0) { array.shift(); }
: Removes elements from the end and beginning of the array, respectively.Pros and Cons
Here's a brief analysis of each approach:
array.length = 0
:array = []
:.splice(0)
:splice()
method's implementation.while (array.length > 0) { array.pop(); }
and while (array.length > 0) { array.shift(); }
:Library Usage
The benchmark does not explicitly use any libraries, but it relies on JavaScript's built-in Math.random()
function to populate the array with random numbers.
Special JS Features
There are no special JS features or syntax used in this benchmark. It only employs standard JavaScript syntax and built-in functions.
Other Alternatives
Other approaches to clearing and manipulating arrays could include:
for
loop to iterate over the array's indices.Array.prototype.fill()
to fill an array with a specific value, then removing elements as needed.Array.prototype.filter()
, Array.prototype.forEach()
, or other array methods to manipulate and clear the array.Keep in mind that each approach has its trade-offs, and the best choice depends on the specific requirements of your use case.