r/computerscience • • 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?

22 Upvotes

39 comments sorted by

View all comments

Show parent comment

1

u/SirClueless May 29 '25

I don’t think the distinction you’re drawing makes much sense. Adding or removing memoization can change a procedure’s behavior, that’s true. But this is true of mathematically idempotent functions in practice too: memoizedFibonacci(1000) takes 1ms to compute while fibonacci(1000) takes trillions of times longer than the heat death of the universe, “just caching” is not something you can ever skip thinking about.

1

u/custard130 May 29 '25

i didnt mean that just caching values cant be useful / isnt important sometimes

i meant that there are things that need more than just basic caching to make them behave correctly

the kinds of problems where idempotency specifically is important rather than just caching for performance in my experience generally have network connections involved and the two generals problem rearing its ugly head

a "pure" function you can cache the result no problem like your fibonacci example or many other more useful versions

while ofc its just an example, if 1000 terms of fibonacci did actually take "trillions of times longer than the heat death of the universe" then your memoized version would also take that long the first time it ran, it would only be fast from the 2nd call onwards which would never happen. if for some reason your application did regularly need that value you would need find some other way to compute it and then bake the value into your app as a constant so memoizing still isnt a universal solution

as it is i feel like thats within the capabilities of modern cpus to calculate in ms/seconds not lifetime of the universe

while im not sure exactly how to write the code to do it, it would require 1000 x 700 bit additions,

lets say a 700 bit addition takes 1,000,000x the amount of time that a native 64 bit addition would take, if my maths is right the computer im writing this on can perform ~80 billion 64 bit additions per second, or 80 thousand of my hypothetical 700 bit addions, or ~15ms

while maybe not up to 1000, i expect the first 100 or so terms are actually faster for a cpu to compute than fetching a "cached" value from ram and the first dozen maybe even faster than the cpus onboard cache

1

u/SirClueless May 29 '25 edited May 29 '25

the kinds of problems where idempotency specifically is important rather than just caching for performance in my experience generally have network connections involved and the two generals problem rearing its ugly head

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.

if 1000 terms of fibonacci did actually take "trillions of times longer than the heat death of the universe" then your memoized version would also take that long the first time it ran, it would only be fast from the 2nd call onwards which would never happen

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:

def fibonacci(n):
    if n <= 1:
        return 1
    return fibonacci(n-1) + fibonacci(n-2)

@functools.cache
def memoized_fibonacci(n):
    if n <= 1:
        return 1
    return memoized_fibonacci(n-1) + memoized_fibonacci(n-2)

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.

1

u/custard130 May 29 '25 edited May 29 '25

i guess i missed that it would help the intermediate steps, mainly because i wasnt thinking about implmenting it recursively (i was actually thinking of a youtube video where James Sharman got his 8 bit cpu to compute up to max 16 bit fibonacci number)

while maybe your example isnt the worst, there is a balance to be found between adding caching to an inneficient solution vs using a more efficient solution. and tbh i feel like a vast majority of the time people get that wrong

if instead of the 1000th term of fibonacci, you wanted the 1000th triangle number, would you consider a memoized recursive form of that "correct"?

back to fibonacci i feel like if i actually needed large fibonacci numbers i would end up with something along the lines of

fibonacci(n) {
    if (n <= 2)
        return 1;
    data[3];
    data[0] = data[1] = 1;
    for (i = 2; i <= n; i++) {
        data[i % 3] = data[i - 1 % 3] + data[i - 2 % 3];
    }
    return data[n % 3];
}

which would also work in O(n)

while they may scale linearly, with an operation as fundamental as addition (which modern computers will run billions of additions per second without even breaking a sweat) cache lookups and function calls are a significant overhead

there may even be a O(1) version with Binet's formula though im not sure on the accuracy of that one

1

u/SirClueless May 30 '25

I agree with your points here. Adding caching to an inefficient solution is usually worse than using a more efficient solution. Your example of triangle numbers is apt, it’s hard to imagine an implementation of a function that computes them where caching would be a net win. And it’s true that the mere fact that memoizing helps when computing Fibonacci numbers is a pretty good indication that a better algorithm exists.

But don’t these points broadly support my original claim? If memoizing a pure function without side effects is rarely useful as compared to using a better algorithm, then doesn’t that imply the main reasons to reach for memoization are when the function is impure or has side effects? “Compute the nth Fibonacci number” is not a natural place to reach for memoization precisely because the only possible effect it can have is to speed it up, and there’s probably better ways to speed it up. “Get me the current time zone offset of New York” is a highly natural function to want to memoize, precisely because it’s clearly not idempotent and depends on the current date and a lookup into some system timezone DB, and caching it turns it from some non-idempotent fragile lookup that can change in the middle of a computation into something that’s reliable and idempotent and can be freely called from anywhere.

1

u/custard130 May 30 '25

ye i guess we got caught up in the pure function side of the topic where memoization/caching is simple to add but maybe not always the best solution

where it can be useful/optimal imo is for situations where dara is being loaded from a remote source that doesnt change very often (often enough that the value cant just be baked in as a constant but rare enough that the source doesnt need to be checked on every call)

or for expensive computations where the result is needed many times and there isnt a better alternative

1

u/Classic-Try2484 May 30 '25

This is wrong. The function should always return its source of truth. The function should be called only once and the value shared for the relevant services of that call. Turning the function idempotent breaks it.

1

u/Classic-Try2484 May 30 '25

Memoized fib is O(1) amortized analysis.

1

u/SirClueless May 30 '25

It is not. It is O(1+ n / k) where n is the largest value input value among the requests and k is the number of requests, but we can’t relate n to k without additional information so this might not be O(1).

1

u/Classic-Try2484 May 30 '25 edited May 30 '25

I might disagree with this implementation. But correctly written it is O(1). Or perhaps you didn’t see amortized analysis.

One can also argue a first call to fib(k) will generate k calls as the function is recursive so n == k even on the first call

1

u/SirClueless May 30 '25

Let’s assume memoized Fib has a linear-time worst case in n. Then the amortized worst case is still proportional to n.

Note that this case is different from a typical amortized analysis. Usually when you use amortized analysis, it’s because the algorithm does some expensive work, but you can bound this work by the number of requests you make. For example, the time spent rehashing a hash table can be bounded by the number of requests you make. i.e. the total amount of work is O(n) and the number of requests is n, so the amortized worst case is O(1). But here the total amount of work is O(n) but the number of requests is k, so you can’t do the same trick.

For a concrete counter-example, consider if the sequence of computations was fib(1), fib(2), fib(4), fib(8)… i.e. at each step i we compute fib(2i). Then after k steps the total amount of work we’ve done is O(2k+1) and the total amount of steps is k, so the amortized cost is O(2k+1 / k) which is not O(1). The amount of extra work we do at each step never decreases, it always continues increasing exponentially, and we never see the benefits of amortization on our average runtime because the most-recent step always dwarfs all the work we’ve done before.

1

u/Classic-Try2484 May 30 '25

When you call fib n it calls fib n-1 so you always have at least n calls. The cost of each is O(1)

1

u/Classic-Try2484 May 30 '25

I’ll agree finding the value of fib x is O(n) but the function that computes it is O(1) average case.

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).

→ More replies