<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var arr = [];
var size = 10
for (let i = 0; i < 1E6; i++) {
arr.push(i);
}
const result = arr.reduceRight((res,_,__,self) => [res, self.splice(0, size)],[]);
_.chunk(arr, 10);
const result = [];
while (arr.length) {
const chunk = arr.splice(0, size)
result.push(chunk);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
chunks by reduceRight | |
chunks by lodash | |
splice from the beginning |
Test name | Executions per second |
---|---|
chunks by reduceRight | 13165212.0 Ops/sec |
chunks by lodash | 4925377.0 Ops/sec |
splice from the beginning | 13880723.0 Ops/sec |
Benchmark Overview
The provided benchmark measures the performance of three different approaches to chunking an array: splice from the beginning
, reduceRight
, and using the Lodash library (_chunk
).
Chunking Approaches
reduceRight
method on the array to create chunks. It iterates over the array from right to left, applying a callback function to each element that returns the current chunk.reduceRight
._chunk
function to create chunks from the array.Library Use
In this benchmark, the lodash
library is used for the Lodash chunking approach. The lodash.min.js
file is included via a script tag in the HTML preparation code.
Special JavaScript Feature or Syntax
The benchmark uses the _
variable as a common scope reference in the _chunk
function from Lodash, which is a convention in JavaScript to use _
as a reserved name for variables that don't have an explicit let
declaration.
Other Alternatives
If you wanted to implement chunking using other approaches, some alternatives could be:
Array.prototype.slice()
and iterating over the array manually.Array.prototype.reduce()
or Array.prototype.map()
.Keep in mind that each approach has its trade-offs, and the best choice will depend on the specific requirements of your project.