var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"];
var firstFruits = [];
for (var i = 0; i < fruits.length; i = i+3) {
firstFruits.push(fruits[i]);
};
for(var i = 0; i < fruits.length; i++) {
fruits.splice(i+1,2);
}
var filtered = fruits.filter(function(_, i) { return (i % 3 == 0); })
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Push to new array | |
Splice | |
Filter |
Test name | Executions per second |
---|---|
Push to new array | 21465130.0 Ops/sec |
Splice | 13790847.0 Ops/sec |
Filter | 34620820.0 Ops/sec |
Let's dive into explaining the JavaScript microbenchmark on MeasureThat.net.
Benchmark Definition
The benchmark is defined by providing a script preparation code and an HTML preparation code (which is empty in this case). The script preparation code defines an array of fruit names with some numbers embedded, representing the test data. The HTML preparation code is not used in this benchmark.
Test Cases
There are three individual test cases:
firstFruits
and then pushes every third element from the original fruits
array into it.i+1
from the original fruits
array.fruits
array to only include elements whose index is a multiple of 3.Options Compared
The three test cases compare different approaches for manipulating arrays:
push()
with creating a new array (Push to new array
)splice()
without modifying the original array (Splice
)filter()
with filtering out elements based on their index (Filter
)Pros and Cons of Each Approach
Push to new array
Splice
push()
.push()
or filter()
, may have performance issues if not used carefully.Filter
splice()
since it involves creating a new filtered array, which can lead to more memory allocation.Libraries Used
None are explicitly mentioned in this benchmark. However, JavaScript's built-in methods like Array.prototype.push()
, Array.prototype.splice()
, and Array.prototype.filter()
are used.
Special JS Feature or Syntax
The use of the arrow function (function(_, i) { return (i % 3 == 0); }
) is a special feature. It provides a concise way to define small anonymous functions without declaring them as full-fledged functions using the function
keyword.
Alternatives
If you were to rewrite these benchmarks, consider the following alternatives:
push()
), consider using slice()
or other methods to extract elements from the original array.splice()
, consider handling edge cases like when the start index is out of range or when there are not enough elements left in the array.map()
or every()
instead of filter()
if performance is critical.Keep in mind that these alternatives would depend on your specific requirements and constraints. The original approach provides a straightforward way to demonstrate each method's behavior.