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?
22
Upvotes
View all comments
Show parent comment
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