<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var test = Array.from({
length: 100000
}, () => Math.random())
test.slice(0,5000)
_.chunk(test,5000)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Native slice | |
lodash chunk |
Test name | Executions per second |
---|---|
Native slice | 1280061.5 Ops/sec |
lodash chunk | 5856.7 Ops/sec |
I'd be happy to explain the benchmark and its components.
Benchmark Overview
The MeasureThat.net website allows users to create and run JavaScript microbenchmarks, including this specific benchmark: native-slice-vs-chunk
. The benchmark compares the performance of two approaches: using the native Array.prototype.slice()
method versus using the _chunk()
function from the Lodash library.
Script Preparation Code
The script preparation code for the benchmark is:
var test = Array.from({ length: 100000 }, () => Math.random());
This code creates an array of 100,000 random numbers and assigns it to the test
variable. This array will be used as the input data for the benchmark.
Html Preparation Code
The HTML preparation code includes a link to the Lodash library:
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
This script tag loads the Lodash library, which provides the _chunk()
function used in one of the benchmark test cases.
Test Cases
The benchmark consists of two individual test cases:
Array.prototype.slice()
method to extract a subset of 5,000 elements from the input array test
.test.slice(0,5000)
_chunk()
function to divide the input array into chunks of 5,000 elements._.chunk(test,5000)
Comparison
The benchmark compares the execution time (measured in executions per second) for both test cases. The results will show which approach is faster and more efficient.
Pros and Cons
Here are some pros and cons of each approach:
Array.prototype.slice()
method.Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks such as array manipulation, string manipulation, and more. The _chunk()
function is one of its many functions that can divide an input array into smaller chunks.
Special JS Feature/Syntax
This benchmark does not use any special JavaScript features or syntax. It only relies on standard JavaScript functionality and the Lodash library for the chunk
test case.
Alternatives
Other alternatives to compare with the native slice and Lodash chunk approaches include:
Array.prototype.slice()
with a custom loop or using Array.prototype.map()
.Keep in mind that these alternatives may not be directly comparable to the native Array.prototype.slice()
method or the Lodash _chunk()
function, as they may have different performance characteristics or use cases.