<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var values = new Array(200 * 200 * 4)
var chunks = _.chunk(values, 4)
const chunk = (input, size) => {
return input.reduce((arr, item, idx) => {
if (idx % size === 0) {
arr.push([item]);
}
else {
arr[arr.length - 1].push(item);
}
return arr;
}, []);
}
var 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]];
}, []);
}
var chunks = chunk(values, 4)
const chunk = (input, size) => {
const arr = [];
for (let i = 0; i < input.length; i += size) {
arr.push(input.slice(i, i + size));
}
return arr;
};
var chunks = chunk(values, 4)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash | |
native new | |
native old | |
native for loop |
Test name | Executions per second |
---|---|
lodash | 2241.1 Ops/sec |
native new | 6778.1 Ops/sec |
native old | 7381.5 Ops/sec |
native for loop | 1640.2 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Overview
The benchmark measures the performance of three different approaches to chunking an array: using Lodash (lodash
), a custom native new
function, and a custom native for loop
function. The benchmark tests how fast each approach can divide an array of 200x200 elements into chunks of size 4.
Test Cases
chunk
that takes an input array and a size as arguments. It uses the reduce
method to create chunks of the specified size. The native new
approach is likely optimized for performance, but its implementation details are not shown in the benchmark.chunk
that takes an input array and a size as arguments. However, this implementation uses a different logic to create chunks, which may be less efficient than the native new
approach.Options Compared
The three test cases compare different approaches to chunking an array:
chunk
function, which is likely optimized for performance.reduce
method to create chunks. This approach may be more efficient than using a library function.Pros and Cons
Here are some pros and cons of each approach:
native new
, likely less efficient than Lodash.Other Considerations
When choosing an approach to chunking an array, consider the following factors:
Alternatives
If you don't want to use Lodash or implement your own chunking logic, consider the following alternatives:
chunk
in React.Keep in mind that the best approach depends on your specific use case and requirements.