<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js'></script>
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'], 3);
chunk(['a', 'b', 'c'], 3);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
Native |
Test name | Executions per second |
---|---|
Lodash | 5650757.0 Ops/sec |
Native | 8009918.5 Ops/sec |
Let's dive into the explanation.
Benchmark Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The benchmark in question compares the performance of two approaches for chunking an array: Lodash's chunk
function (native implementation) vs native JavaScript implementation (chunk
).
Options Compared
The benchmark tests two options:
chunk
function: A utility function from the popular JavaScript library Lodash that provides a way to split an array into smaller chunks.chunk
function using pure JavaScript, without relying on any external libraries.Pros and Cons
Native JavaScript Implementation (Lodash)
Pros:
Cons:
Lodash's chunk
Function
Pros:
Cons:
Library: Lodash
Lodash is a popular JavaScript utility library that provides various functions for tasks like array manipulation, string formatting, and more. The chunk
function is one of its many utility functions, designed to split an array into smaller chunks.
Special JS Feature/ Syntax
There are no special JS features or syntax used in this benchmark.
Other Alternatives
If you're interested in exploring other approaches for chunking arrays, consider the following alternatives:
slice()
method to create a new array by extracting a subset of elements from an existing array. This approach is simple but may not be as efficient as native implementation or Lodash's chunk
.Keep in mind that these alternatives may not be as efficient or well-tested as native implementation or Lodash's chunk
function.