const fibonacci = (n) => {
if (n <= 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
};
fibonacci(20);
const memoize = function(func) {
var stringifyJson = JSON.stringify,
cache = {};
var cachedfun = function() {
var hash = stringifyJson(arguments);
return hash in cache ? cache[hash] : (cache[hash] = func.apply(this, arguments));
};
cachedfun.__cache = function() {
cache.remove ||
(cache.remove = function() {
var hash = stringifyJson(arguments);
return delete cache[hash];
});
return cache;
}.call(this);
return cachedfun;
};
const fibonacci = memoize((n) => {
if (n <= 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
});
fibonacci(20);
const memoize = function(func) {
const cache= {}
return (args) => {
const n = args[0]
if (n in cache) {
return cache[n];
} else {
const result = func(n)
cache[n] = result
return result
}
}
};
const fibonacci = memoize((n) => {
if (n <= 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
});
fibonacci(20);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Fib Base | |
Fib memoized 1 | |
Fib memoized Tommy |
Test name | Executions per second |
---|---|
Fib Base | 8829.5 Ops/sec |
Fib memoized 1 | 46239.4 Ops/sec |
Fib memoized Tommy | 654223.2 Ops/sec |
I'll dive into explaining the benchmark.
Benchmark Overview
The benchmark tests the performance of two implementations of the Fibonacci sequence: a baseline implementation (Fib Base
) and two memoized versions (Fib memoized 1
and Fib memoized Tommy
). The benchmark uses a JavaScript function to calculate the nth Fibonacci number, which is then executed multiple times in a loop.
Options Compared
The three options being compared are:
Fib Base
): This implementation calculates each Fibonacci number from scratch, without any optimization or caching.Fib memoized 1
): This implementation uses a technique called memoization to cache previously computed Fibonacci numbers. It stores the results in an object and reuses them instead of recalculating them.Fib memoized Tommy
): This implementation is similar to Memoized Version 1, but with some minor differences in the caching logic.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Fib Base
):Fib memoized 1
):Fib memoized Tommy
):Library/Technique Used
Neither of the memoized versions uses a separate library. Instead, they rely on a simple object to store the cached values. The memoize
function in both implementations creates this object and manages the caching logic.
Special JS Features/Syntax
There are no special JavaScript features or syntax used in this benchmark. It's purely functional programming with loops.
Other Alternatives
If you were to implement a memoized Fibonacci sequence, some alternative approaches could include:
lru-cache
to handle caching and storage.These alternatives would provide additional optimization opportunities, but also introduce new complexity and overhead.