function defaultEqualityCheck(a, b) {
return a === b
}
function defaultMemoize_original(func, equalityCheck = defaultEqualityCheck) {
let lastArgs = null
let lastResult = null
return (args) => {
if (
lastArgs === null ||
lastArgs.length !== args.length ||
!args.every((value, index) => equalityCheck(value, lastArgs[index]))
) {
lastResult = func(args)
}
lastArgs = args
return lastResult
}
}
function defaultMemoize_optimized(func, equalityCheck = defaultEqualityCheck) {
const isEqual = (value, index) => equalityCheck(value, lastArgs[index])
let lastArgs = null
let lastResult = null
return (args) => {
if (
lastArgs === null ||
lastArgs.length !== args.length ||
!args.every(isEqual)
) {
lastResult = func(args)
}
lastArgs = args
return lastResult
}
}
function combine(a, b) {
return { combined: a + b };
}
var combine_original = defaultMemoize_original(combine);
var combine_optimized = defaultMemoize_optimized(combine);
var NUM_REPEAT = 50000;
let result1 = 0;
for (let i = 0; i < NUM_REPEAT; ++i)
result1 += combine_original(1, 2).combined;
let result2 = 0;
for (let i = 0; i < NUM_REPEAT; ++i)
result2 += combine_optimized(1, 2).combined;
let result3 = 0;
for (let i = 0; i < NUM_REPEAT; ++i)
result3 += combine(1, 2).combined;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Original defaultMemoize | |
Optimized defaultMemoize | |
No memoization |
Test name | Executions per second |
---|---|
Original defaultMemoize | 284.4 Ops/sec |
Optimized defaultMemoize | 292.6 Ops/sec |
No memoization | 321.6 Ops/sec |
Let's break down what's being tested in this benchmark.
The test cases are designed to compare the performance of three different versions of a memoization function, which is a technique used to optimize repetitive computations by caching their results.
Memoization basics
In this context, memoization is a technique where the result of an expensive computation (in this case, a simple addition) is cached and reused when the same inputs occur again. This avoids redundant calculations, reducing the overall execution time.
The benchmark defines three different versions of a defaultMemoize
function:
isEqual
that compares values at specific indices (in this case, the first value). It still uses the same basic approach to memoization but with some optimizations.Test cases
There are three test cases:
combine(1, 2)
) repeated NUM_REPEAT
times and measures the execution time.defaultMemoize
.Pros and cons
Here are some pros and cons of each approach:
isEqual
which may add complexity.Other considerations:
combine(1, 2)
) to demonstrate the memoization technique. In real-world scenarios, this might not be as representative of actual usage.Alternatives
If you were to modify or extend these benchmarks, some alternatives to consider:
lru-cache
.These considerations can help refine the benchmark and provide a more comprehensive understanding of the performance differences between these memoization approaches.