<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var values = new Array(200 * 200 * 4);
const chunks = _.chunk(values, 4);
const chunk = (input, size) => {
return input.reduce((arr, item, idx) => {
return idx % size === 0
? [arr, [item]]
: [arr.slice(0, -1), [arr.slice(-1)[0], item]];
}, []);
};
const chunks = chunk(values, 4);
const chunk = (arr, chunkSize = 1, cache = []) => {
const tmp = [arr]
if (chunkSize <= 0) return cache
while (tmp.length) cache.push(tmp.splice(0, chunkSize))
return cache
}
const chunks = chunk(values, 4);
var chunks = [];
for (var i = 0; i < values.length; i += 4) {
chunks.push(values.slice(i, i + 4));
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash | |
you-dont-need | |
youmightnotneed | |
custom |
Test name | Executions per second |
---|---|
lodash | 527.1 Ops/sec |
you-dont-need | 1687.1 Ops/sec |
youmightnotneed | 1.9 Ops/sec |
custom | 108.7 Ops/sec |
Let's break down the provided JSON and benchmark information to understand what is being tested.
Benchmark Definition
The benchmark aims to compare the performance of different approaches to chunking an array in JavaScript. The chunk()
function is used to split the input array into smaller subarrays, each with a specified size (in this case, 4).
Options Compared
Four options are being compared:
_chunk
function from the Lodash library.chunk()
function without using any libraries.chunk()
function, which is similar to the previous one but has some minor differences in its logic.Pros and Cons
Here's a brief overview of the pros and cons of each approach:
splice
instead of slice
).Library Usage
The Lodash
library is used for its _chunk
function, which provides a simple and efficient way to chunk an array. The library's implementation is likely optimized for performance, making it a good choice when speed is crucial.
Special JS Features or Syntax
None of the benchmarked implementations explicitly use any special JavaScript features or syntax that would impact their performance significantly (e.g., async/await
, generators, Web Workers).
Other Alternatives
If you're looking for alternative approaches to chunking an array in JavaScript, consider:
chunk
function similar to Lodash's implementation.map()
and reduce()
: While not recommended for performance-critical code, this approach can be used as an educational exercise or when working with very small arrays.In summary, the benchmark provides a comparison of different approaches to chunking an array in JavaScript, highlighting the trade-offs between using a library (Lodash), custom implementations (You-Dont-Need
and YouMightNotNeed
), and a simple iterative approach (Custom
).