<script src="https://cdn.jsdelivr.net/npm/immer@4.0.0/dist/immer.umd.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
data = _.range(100)
const reducer = immer.produce((draft, curr) => { draft[0] = 0; });
const answer = data.reduce(reducer, {})
const reducer = (draft, curr) => { draft[0] = 0; return draft; };
const answer = data.reduce(reducer, {})
const answer = data.reduce((acc, curr) => ({
acc,
0: 0,
}), {});
const answer = immer.produce({}, draft => { data.reduce((acc, curr) => { acc[0] = 0; return acc }, draft) });
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
immer | |
Mutate | |
Spread | |
immer pull up |
Test name | Executions per second |
---|---|
immer | 2305.7 Ops/sec |
Mutate | 1096855.8 Ops/sec |
Spread | 34743.4 Ops/sec |
immer pull up | 27485.8 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Overview
The benchmark is designed to compare the performance of three approaches for performing aggregation on an array of numbers:
{...}
) to create a new objectImmer (immer@4)
The first test case uses Immer's produce
function, which returns an immutable version of the original array using a reducer function. The reducer takes two arguments: draft
(the original array) and curr
(an optional value used to update the draft). In this test, draft[0]
is updated to 0, and then the data.reduce
method is called with the reducer as an argument.
Immer (immer pull up)
The second test case uses Immer's produce
function in a slightly different way. Instead of passing curr
explicitly, it passes a callback function that updates the draft directly. This approach is called "pull-up" because it avoids creating an intermediate immutable version of the array.
Mutate
The third test case uses a simple reducer function to update the accumulator (acc
) directly. The difference between this and Immer's approach is that the accumulator is not wrapped in an immutable object.
Spread
The fourth test case uses the spread operator to create a new object with the aggregated value. This approach avoids mutating the original array but requires creating a new object.
Pros and Cons of Each Approach:
Other Considerations:
Alternative Approaches:
map()
and reduce()
separately, which might be more efficient than Immer's approach for smaller arrays.When choosing an approach, consider factors like:
Keep in mind that the optimal approach may vary depending on your specific use case.