r/computerscience • u/dashdanw • May 27 '25
Discussion Does memoizing a function make it truly "idempotent"?
If you cache the result of a function, or say, for instance, check to see if its already been run, and skipping running it a second time make a function truly idempotent?
21
Upvotes
View all comments
Show parent comment
1
u/SirClueless May 29 '25 edited May 29 '25
Completely agree. That was my whole original point: it is valid to want to cache the results of work that is messy and not intrinsically idempotent. In fact, that is typically the most useful kind of work to cache in practice. Memoization is a tool that works for all kinds of work; sometimes it changes the performance of a function and sometimes it changes what a function returns. Both cases are valid and useful, it's not something you can just brush under the rug even in cases where the function you are memoizing is mathematically pure.
This is not true, because fibonacci is defined recursively.
A naive recursive implementation of
fibonacci(n)has exponential time complexity, O(2n). The exact same algorithm but memoized has linear time complexity O(n). This is worst-case time complexity, and includes the first call. For example, in Python:There are of course even faster and more-direct solutions to Fibonacci, but the point was to show an algorithm whose theoretical time complexity changes when you introduce memoization to show that memoization can change the correctness of a function in practice.