s = new Set();
a = [];
for (var i=0; i < 1000; i++) s.add(i*i);
a.splice(0, a.length, s.values());
a.length = 0;
for (var x of s) a.push(x);
a.splice.apply(a, [0, a.length].concat(Array.from(s)));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array.splice | |
for loop | |
array.splice w/o spread |
Test name | Executions per second |
---|---|
array.splice | 20736.8 Ops/sec |
for loop | 96416.4 Ops/sec |
array.splice w/o spread | 108887.3 Ops/sec |
Let's dive into the benchmark and explore what's being tested, compared, and the pros and cons of each approach.
What is being tested?
The benchmark is comparing three different approaches to remove elements from an array in JavaScript:
array.splice(0, a.length, ...s.values())
: This method uses splice
with a starting index of 0, removing all elements from the array and then replaces them with values from the Set
object.a.length = 0; for (var x of s) a.push(x);
: This approach creates a new array by iterating over the values in the Set
object and adding each one to the original array, effectively replacing the existing elements.a.splice.apply(a, [0, a.length].concat(Array.from(s)))
: Similar to the first method, but without using spread syntax (...s.values()
).Options compared
The benchmark is comparing the performance of these three approaches:
array.splice(0, a.length, ...s.values())
:...
syntax (as it creates a new array with the spread operator).a.length = 0; for (var x of s) a.push(x);
:splice
when removing all elements, as it avoids creating an intermediate array.a.splice.apply(a, [0, a.length].concat(Array.from(s)))
:...
syntax, potentially making it faster for large arrays.splice
approach.Library and purpose
In the benchmark preparation code, a Set
object is created and populated with values. A Set
is a data structure in JavaScript that stores unique values, making it efficient for fast lookups and iteration. The library used here is the built-in JavaScript Set
API.
Special JS feature or syntax
The benchmark uses the spread operator (...
) to create an array from the Set
object's values. This is a relatively modern feature introduced in ECMAScript 2018 (ES10). It allows for concise and efficient way to transform sets into arrays.
Other alternatives
If you were to implement this benchmark manually, without relying on pre-existing libraries or built-in functions, you could consider the following approaches:
for
loops with array indexing: a.length = 0; for (var i = 0; i < a.length; i++) { a[i] = undefined; }
filter()
and map()
: a.splice(0, a.length); a = a.filter(x => s.has(x)).concat(s)