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 = [];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set length to zero | |
New empty array |
Test name | Executions per second |
---|---|
Set length to zero | 57570.4 Ops/sec |
New empty array | 56808.1 Ops/sec |
Let's dive into the explanation.
What is being tested?
The provided JSON represents a benchmark test for two different ways of emptying an array in JavaScript: setting its length
property to 0, versus creating a new empty array instance and assigning it to the original array variable.
Test Case 1: Setting length to zero
In this test case, we have an array arr2
that is populated with 10,000 elements using a for
loop. Then, we set its length
property to 0. This approach modifies the existing array object in place, without creating a new instance.
Test Case 2: Creating a new empty array
In this test case, we again have an array arr3
that is populated with 10,000 elements using a for
loop. Then, instead of setting its length
property to 0, we assign a new empty array instance ([]
) to the original array variable. This approach creates a new array object and replaces the old one.
Libraries and features
No external libraries are used in these test cases. The only JavaScript feature employed is the use of an array's length
property to modify its size, which is a standard language construct.
Pros and cons of each approach
Other considerations
Alternatives
Other alternatives for emptying an array in JavaScript include:
splice()
with a negative index, like arr.splice(0, arr.length)
(not tested here).delete
operator with a loop or map()
, which can be slower than setting length to zero.I hope this explanation helps!