<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js'></script>
var test = Array.from({
length: 100000
}, () => Math.random())
const chunkSize = 80;
const chunks = [];
for (let i = 0; i <= test.length; i += chunkSize) {
chunks.push(test.slice(i, i + chunkSize));
}
const chunkSize = 80;
test.reduce((accu, element, idx) => {
if (idx % chunkSize === 0) {
accu.push([]);
}
const chunk = accu[accu.length - 1];
chunk.push(element);
return accu;
}, []);
_.chunk(test,80)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
native slice | |
native reduce | |
lodash chunk |
Test name | Executions per second |
---|---|
native slice | 10737.5 Ops/sec |
native reduce | 414.4 Ops/sec |
lodash chunk | 2973.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Definition
The benchmark is comparing three approaches to chunking an array:
slice()
method to extract chunks from the original array.reduce()
method with a custom callback function to create chunks.chunk()
method from the Lodash library to create chunks.Options Compared
The three approaches are compared in terms of their performance, specifically:
Pros and Cons
Here's a brief overview of the pros and cons of each approach:
Library Used
In this benchmark, the lodash
library is used for its chunk()
method. Lodash is a popular utility library that provides various functions for tasks like array manipulation, string processing, and more.
Special JS Feature/Syntax
There are no special JavaScript features or syntaxes being tested in this benchmark. However, it's worth noting that the use of reduce()
as a chunking approach might be considered an advanced JavaScript concept.
Other Alternatives
If you're looking for alternative approaches to chunking arrays, here are some options:
chunk()
method similar to Lodash.