var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
var copy = data.slice(5);
var copy = data.filter(d => d < 5);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
slice | |
filter |
Test name | Executions per second |
---|---|
slice | 4122917.5 Ops/sec |
filter | 1390271.2 Ops/sec |
What is being tested?
The benchmark measures the performance of two different approaches to slice an array in JavaScript: using Array.slice()
and using the filter()
method with a callback function.
Options compared
Two options are being compared:
Array.slice()
: This method returns a shallow copy of a portion of an array, specified by its start index (inclusive) and end index (exclusive). It is designed to create a new array object containing the elements from the start index up to but not including the end index.Array.filter()
with callback function: This method creates a new array with all elements that pass the test implemented by the provided function.Pros and cons of each approach
Array.slice()
:Array.filter()
with callback function:slice()
, as it iterates over the entire array and creates a new one.Library usage
Neither Array.slice()
nor Array.filter()
uses external libraries. They are native JavaScript methods that work directly with arrays.
Special JS feature or syntax
The benchmark does not use any special JavaScript features or syntax beyond standard ECMAScript 2022 (ES12) support.
Benchmark preparation code
The script preparation code defines an array data
and assigns a slice index to create a copy of the last five elements:
var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
Individual test cases
The benchmark consists of two individual test cases:
slice
: Creates a copy of the last five elements using Array.slice()
.var copy = data.slice(5);
filter
: Filters out elements greater than or equal to 5 using Array.filter()
:var copy = data.filter(d => d < 5);
Latest benchmark result
The latest benchmark result shows that:
slice
test case approximately 4.12 million times per second.filter
test case approximately 1.39 million times per second.Other alternatives
If the author wanted to explore other approaches, they could consider:
Array.prototype.map()
instead of slice()
Array.prototype.slice.call()