Memoization with an argument not behaving as I'd expect #1288
-
Hello everyone 👋 Crystal and Lucky newbie here! Having fun with Lucky so far, and one cool thing I noticed in the documentation is the built-in way of memoizing methods, which even takes the method params into account. According to the documentation: # This is only called once per `id` passed in.
memoize def fetch_user(id : String) : User
make_api_call && UserQuery.new.find(id)
end So I tried a dummy example, like this: class Api::Distances::Index < BrowserAction
route do
["one", "one", "one", "one"].each { |value| memoized_method(value) }
puts "-"*50
["two", "three", "two", "three"].each { |value| memoized_method(value) }
plain_text "Done"
end
memoize def memoized_method(key : String) : String
# something expensive
puts "memoized method called with #{key}"
# return some string value to satisfy the method signature
end
end In my example above, I'd expect to see "one", "two" and "three" written once, the first time the
The memoization works well as long as I call the memoized method with the same argument, again and again, the method is only run once. BUT calling the method again with a different argument seems to "reset" the memoization? Did I misunderstand the documentation, or am I simply making some kind of Crystal-newbie mistake here? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Hey @pabuisson! It only memoizes the last argument it was called with. Looking at the docs now, I can see how you'd get that impression, though. |
Beta Was this translation helpful? Give feedback.
-
@matthewmcgarvey If you've got a way in mind to make the documentation more clear, would you mind opening up a website issue? Happy to get to that at some point to make things clearer. |
Beta Was this translation helpful? Give feedback.
Hey @pabuisson! It only memoizes the last argument it was called with. Looking at the docs now, I can see how you'd get that impression, though.