I am trying to make use of a cache to improve the performance of my Fibonacci method. However, it is still taking a lot of time to compute even fibonacci(40).
import java.util.Scanner;
public class FibWithCache {
public static void main(String args[]) {
System.out.println("Enter Fibonacci index: ");
Scanner sc = new Scanner(System.in);
int index = sc.nextInt();
sc.close();
System.out.println(fibonacci(index));
}
private static long fibonacci(int index) {
long result = 0;
long[] fibCache = new long[200];
if(index==0)
return 0;
else if(index == 1)
return 1;
else if(fibCache[index] != 0)
return fibCache[index];
else {
result = fibonacci(index-1) + fibonacci(index-2);
fibCache[index] = result;
return result;
}
}
}
Why am I unable to benefit from the cache?