<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js'></script>
var arrays = [[1, 2, 3, 4, 5], [5, 2, 10]];
function chunk(input, size) {
const length= input.length;
const chunksLenght= length/size;
if(chunksLenght<0){
return input;
}
const chunks=[];
let index = 0;
for(let i =0 ;i < chunksLenght ; i++){
chunks.push(input.slice(index , index + size));
index += size;
}
// the remainig
if(index < length){
chunks.push(input.slice(index , length));
}
return chunks;
};
_.chunk(['a', 'b', 'c', 'd'], 3);
chunk(['a', 'b', 'c', 'd'], 3);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
Native |
Test name | Executions per second |
---|---|
Lodash | 5288049.0 Ops/sec |
Native | 5827703.5 Ops/sec |
Let's dive into the benchmark.
Benchmark Definition
The provided JSON represents a JavaScript microbenchmark, specifically comparing two approaches to chunking arrays: Lodash's _.chunk
function and a native implementation using a custom chunk
function.
Options Compared
Two options are compared:
_.chunk
function: This is a widely-used utility function in the Lodash library that takes an array and a size as input, splitting the array into chunks of the specified size.chunk
function: The native implementation uses a simple loop to split the array into chunks.Pros and Cons
Here's a brief overview of each approach:
_chunk
function:chunk
function:Library: Lodash
Lodash is a popular JavaScript library that provides various utility functions, including _.chunk
, for working with arrays and other data structures. Its purpose is to simplify common tasks and provide a consistent interface across different browsers and environments.
Special JS Feature/Syntax
There are no special JS features or syntax used in this benchmark. Both implementations use standard JavaScript features, such as arrays and loops.
Benchmark Results
The latest benchmark results show that the native implementation using custom chunk
function outperforms Lodash's _chunk
function on the specific test case provided. This suggests that the custom implementation is more efficient than the library-based approach.
Other Alternatives
If you need to chunk arrays, other alternatives to consider include:
chunk
function similar to Lodash's implementation.Keep in mind that the choice of implementation ultimately depends on your specific requirements, performance needs, and personal preference.