I’m curious what people are doing for memoization in #golang. I’ve looked around and haven’t found great libraries for this which makes me wonder if I’m pursuing the wrong solution to a problem.

Caching the return values of functions based on the params has been useful to reduce load on downstream services, make things a bit faster on average and even add some level of consistency in functions that can be highly variable (which is an odd use case but nonethelass useful). But maybe there’s a different pattern/idiom that’s used in the Go ecosystem?

  • wyrmroot@programming.dev
    link
    fedilink
    English
    arrow-up
    4
    ·
    edit-2
    9 months ago

    In applications where I’ve needed this, I’ve taken a manual approach. Structure the function to return a single Result struct (including an error field), develop a convention for mapping function inputs to a string, then add reads & writes to a map[string]*Result which allows me to return cached values as a shortcut. No idea if it’s the most efficient way, I’ve not actually considered finding a package to handle the process.

    Edit: For more advanced behavior, what are your thoughts on the official memoize package?

    • Kevin Lyda@programming.devOP
      link
      fedilink
      arrow-up
      2
      ·
      9 months ago

      I suppose I should be clearer on the features I want. I’d want to be able to store my cache in memcached or redis and I want the cached data to expire. So for one call, I might want to keep it for five minutes, but another one can stick around for 24 hours.

      The memorize package falls down there.

    • kamstrup@programming.dev
      link
      fedilink
      arrow-up
      1
      ·
      9 months ago

      Pet peeve: don’t use string keys. It invites key collision errors. Use the fact Go supports structs as keys in maps. Safer and more efficient.