Junior — Middle
How does using cache help improve program performance?
sobes.tech AI
Answer from AI
Using cache helps improve the performance of program code by storing the results of expensive operations (such as calculations or database queries) in fast access memory. When the same data is requested again, the program accesses the cache instead of performing the operation anew, significantly reducing response time.
An example in Python using the lru_cache decorator from the functools module:
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(30))
Here, the results of fibonacci function calls are stored in the cache, which speeds up repeated calculations for the same arguments.