memo_wise icon indicating copy to clipboard operation
memo_wise copied to clipboard

Use method-specific instance variables for methods that take arguments

Open JacobEvelyn opened this issue 3 years ago • 1 comments

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 a data! and a data 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.
  • 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 or freeze method
  • 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!

JacobEvelyn avatar Dec 07 '21 14:12 JacobEvelyn

I like retaining the array for zero-arity methods

ms-ati avatar Dec 07 '21 16:12 ms-ati