memo_wise
memo_wise copied to clipboard
Use method-specific instance variables for methods that take arguments
This was a suggestion made by @sampersand in the RubyConf Discord channel for our recent talk. The idea is that instead of using @_memo_wise
for all method types, we'd use a different instance variable for each method, like @_memo_wise_method_#{method_name}
. This should save us an array lookup for a slight performance boost.
There are a few challenges:
- we'd need to avoid name collisions, for example when memoizing both a
data?
and adata!
and adata
method- probably a simple
.sub("?", "__qmark__").sub("!", "__bang__")
would be sufficient - @jemmaissroff may have insight into whether there's a max instance variable length to be worried about (or a length at which performance decreases)
- if so, we could instead use a scheme like
@_memo_wise_method_#{counter}
or use UUIDs, etc.
- if so, we could instead use a scheme like
- probably a simple
- to support frozen objects we need to ensure that these instance variables are initialized to empty hashes before freezing
- this could probably be done either in an overridden
initialize
orfreeze
method
- this could probably be done either in an overridden
- this approach will not support resetting and presetting zero-arity methods on frozen objects
- a simple path forward would be to continue using our array for zero-arity methods
- are there good alternatives?
Would love discussion on this idea and its tradeoffs!
I like retaining the array for zero-arity methods