marius311 / Memoization.jl

Easily and efficiently memoize any function, closure, or callable object in Julia.
MIT License
99 stars 2 forks source link

Memoization and include(...) #29

Closed fps closed 1 year ago

fps commented 1 year ago

Hi,

I am playing around with this package since it would be nice to memoize some things, but it seems it's not working for my particular case.. Here is one file:

test_memoization.jl:

import Memoization

Memoization.@memoize function f(x)
    sleep(2)
    x
end

This works fine if used from the REPL,

julia> include("20 gantry data\\test_memoization.jl")
f (generic function with 1 method)

julia> f(1) # this call takes two seconds
1

julia> f(1) # this call returns immediately
1

But now if I add a second file into the mix, test_memoization2.jl:

include("test_memoization.jl")

x = f(1)

Then this happens:

julia> include("20 gantry data\\test_memoization2.jl") # this call takes two seconds
1

julia> include("20 gantry data\\test_memoization2.jl") # this one as well
1

Is my use of include too naive? Will I have to switch to a more "usual" project structure? Using modules, etc?

Kind regards and thanks for providing this package :)

fps commented 1 year ago

Hmmm, OK, yeah, I was naive...

using Memoization

@memoize function f(x); sleep(2); x; end

f(1) # sleeps

@memoize function f(x); sleep(2); x; end

f(1) # sleeps again

which is not _really_surprising since the function is redefined.. Which is what happens when I reinclude my code snippets..

marius311 commented 1 year ago

Thanks! And thats right, whenever you redefine a memoized function, the cache for all methods of that function are cleared to be safe to make sure you never get the wrong answer. This could be improved to be smarter and only clear the cache when its really needed. If this is something you really need, feel free to open an issue, its something I could look into.