const memo = {}
function fibonacci(n) {
if (n <= 1) return n;
if (memo[n]) return memo[n]
memo[n] = fibonacci(n-1) + fibonacci(n-2)
return memo[n]
}
fibonacci(40)
const cache = new Map();
function fibonacci(n) {
if (n <= 1) return n;
if (cache.has(n)) {
return cache.get(n);
}
cache.set(n, fibonacci(n-1) + fibonacci(n-2))
return cache.get(n)
}
fibonacci(40)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object | |
Map |
Test name | Executions per second |
---|---|
Object | 533428.6 Ops/sec |
Map | 318316.2 Ops/sec |
The benchmark defined tests two different approaches for memoization, which is an optimization technique used to improve the performance of functions by caching previously computed results. The two approaches evaluated are using a regular JavaScript object and using the Map
object from the JavaScript standard library for caching. The benchmark specifically measures the performance of these approaches in calculating Fibonacci numbers.
Memoization using Object
memo
) to store the results of previously computed Fibonacci numbers. When the function is called with an argument, it checks if the result for that argument already exists in memo
.n
is less than or equal to 1, it returns n
.memo[n]
exists, it directly returns the cached result.memo
before returning it.Memoization using Map
Map
object (cache
) to store the results of Fibonacci calculations. Unlike a regular object, a Map maintains the insertion order of its elements and allows for keys of any data type, which can be beneficial.n
is less than or equal to 1 and returns n
if true.cache.has(n)
to check if the value is already computed and stored, and if so, retrieves it using cache.get(n)
.cache.set(n, ...)
, and retrieves the cached result.The benchmark results show the following executions per second for each approach:
Pros:
Cons:
memo
object is referenced, which could be a problem in long-running applications.Pros:
Object.prototype
, eliminating potential key collisions with inherited properties.Cons:
has
, get
, and set
).Choose between these two approaches based on your application's requirements:
Using an ES6 WeakMap: A WeakMap
can be used similarly to a regular Map but offers garbage collection of keys that are not being referenced elsewhere. This can prevent memory leaks.
Memoization Libraries: There are various libraries available (like lodash.memoize
) that provide robust implementations of memoization strategies that handle different edge cases and enhance simplicity for the developer.
Using Higher-Order Functions: You can create a higher-order function that wraps your Fibonacci function and takes care of memoization internally, which can streamline the logic.
In conclusion, the choice of memoization technique depends largely on the specific use case, performance needs, and type of keys you plan to use, with both the Object and Map approaches presenting their own distinctive advantages and disadvantages.