<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 chunkfunction = (arr, chunkSize = 1, cache = []) => {
const tmp = [arr]
if (chunkSize <= 0) return cache
while (tmp.length) cache.push(tmp.splice(0, chunkSize))
return cache
}
var chunks = chunkfunction(values, 4)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash | |
native |
Test name | Executions per second |
---|---|
lodash | 1116.2 Ops/sec |
native | 4.3 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares two approaches to chunking (dividing) an array of values into smaller chunks:
lodash
approach uses the chunk()
function from the Lodash library, which takes an array and a chunk size as input and returns an array of subarrays.chunk()
function using a recursive loop that pushes chunks to a cache.Options Compared
The two approaches are compared in terms of performance (measured by executions per second). This benchmark tests the speed of each approach for chunking an array of 200,000 elements with a chunk size of 4.
Pros and Cons of Each Approach
Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for array manipulation, string formatting, object traversal, and more. The chunk()
function is just one example of the many useful utilities provided by Lodash.
Test Case Explanation
The test case uses two different approaches:
chunk()
function from Lodash to divide it into chunks of size 4.chunk()
function using a recursive loop that pushes chunks to a cache. It uses the same input array as the Lodash example.Other Considerations
This benchmark highlights the trade-offs between using established libraries (like Lodash) and implementing custom solutions in JavaScript. When to choose each approach depends on factors like performance requirements, code complexity, and development speed.
In general:
Alternatives
Other alternatives to Lodash for array manipulation include:
chunk()
method directly on arrays (although this is not a standard method).In summary, this benchmark compares two approaches to chunking an array: using the chunk()
function from Lodash and implementing a custom solution in native JavaScript. The choice between these approaches depends on performance requirements, code complexity, and development speed.