Memoization in Elixir

almirsarajcic

almirsarajcic

Created 1 month ago

Coming to Elixir from Ruby, you probably miss wonderful memoization syntax:

class Product
  def info do
    @info ||= expensive_api_request
  end

  # ...
end

Every subsequent call to Product.info will use the in-memory value of the @info attribute.

We can achieve the same in Elixir in different ways, but one of the easiest is using the memoize package.

defmodule Product do
  use Memoize

  defmemo info(product_id) do
    expensive_api_request(product_id)
  end
end

There are more complex examples including expiry time, invalidation, etc., so make sure to check out the documentation: https://hexdocs.pm/memoize/readme.html.