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 30 '25
Are you saying that if you sample all of the fib() calls in the runtime of the program you will find that on average they took constant time?
I agree, but how does that help you as a caller of fib()? When you call fib(), you can expect it to take O(n) time. If you call it k times, you only pay the cost once. So O(n / k). If I call fib(10,000,000) 5 times, the amortized runtime is ~ 2,000,000 calls of fib() per query.
If things worked the way you say, then every recursive function would be O(1) amortized, but the number you're computing makes little sense. The useful work you performed is to answer some arbitrary k queries from the user, and there's no way to say how k is related to n so the best you can say is that this is O(n / k).