<script src="https://www.jsdelivr.com/package/npm/memoizee"></script>
function fibonacci(num){
var a = 1, b = 0, temp;
while (num >= 0) {
temp = a;
a = a + b;
b = temp;
num--;
}
return b;
}
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 Iterative | |
Fib Tommy |
Test name | Executions per second |
---|---|
Fib Iterative | 79596240.0 Ops/sec |
Fib Tommy | 691704.4 Ops/sec |
Let's break down the provided benchmark and its test cases to understand what's being tested.
Benchmark Overview
The benchmark, titled "Fib Now 4," consists of two individual test cases: "Fib Iterative" and "Fib Tommy." The benchmark is designed to measure the performance of different approaches for calculating the Fibonacci sequence.
Test Case 1: Fib Iterative
This test case uses a simple iterative approach to calculate the Fibonacci sequence. The JavaScript code defines a function fibonacci
that takes an integer num
as input and returns the num
-th Fibonacci number. The function uses a while loop to calculate the Fibonacci numbers iteratively.
Test Case 2: Fib Tommy
This test case uses memoization, a technique where previously calculated results are stored in a cache to avoid redundant calculations. The JavaScript code defines a function fibonacci
that takes an integer n
as input and returns the n
-th Fibonacci number. This implementation uses the memoizee
library, which provides a simple way to implement memoization.
Memoizee Library
The memoizee
library is used in Test Case 2 to implement memoization for the Fibonacci sequence calculation. The library provides a function memoize
that takes another function as input and returns a new function with memoized behavior. In this case, the memoize
function is used to wrap the original Fibonacci function, caching its results for future calls.
Pros and Cons of Different Approaches
Special JS Feature/Syntax
There are no special JavaScript features or syntax used in these test cases. The code is standard JavaScript, and the use of memoization is a common technique to improve performance.
Other Alternatives
Other approaches that could be used to calculate the Fibonacci sequence include:
Benchmark Considerations
When interpreting the benchmark results, consider the following:
By considering these factors and approaches, you can gain insights into the relative performance of different methods for calculating the Fibonacci sequence.