Phlex.FIFOCache (phlex v0.3.0)

Copy Markdown View Source

First-In-First-Out cache for attribute strings.

Similar to phlex-ruby's FIFO cache, this provides a simple in-memory cache that evicts entries on a first-in-first-out basis when the maximum size is reached.

Configuration

The cache has configurable limits:

  • max_bytesize: Maximum total size of all cached values in bytes (default: 2_000_000 = ~2MB)
  • max_value_bytesize: Maximum size of a single cached value in bytes (default: 2_000_000)

Examples

cache = Phlex.FIFOCache.new(max_bytesize: 1_000_000)
cached_value = Phlex.FIFOCache.fetch(cache, key, fn ->
  generate_attributes(attrs)
end)

Summary

Functions

Returns the current size of the cache in bytes.

Clears all entries from the cache.

Fetches a value from the cache, or computes it if not present.

Creates a new FIFO cache.

Returns the number of entries in the cache.

Types

t()

@type t() :: %Phlex.FIFOCache{
  bytesize: non_neg_integer(),
  max_bytesize: non_neg_integer(),
  max_value_bytesize: non_neg_integer(),
  store: :ets.tid()
}

Functions

bytesize(fifo_cache)

Returns the current size of the cache in bytes.

clear(cache)

Clears all entries from the cache.

fetch(cache, key, fun)

Fetches a value from the cache, or computes it if not present.

If the key exists in the cache, returns the cached value. Otherwise, calls the function to compute the value, caches it, and returns it.

Values larger than max_value_bytesize are not cached.

Examples

cache = Phlex.FIFOCache.new()
value = Phlex.FIFOCache.fetch(cache, {:attrs, [class: "foo"]}, fn ->
  generate_attributes([class: "foo"])
end)

new(opts \\ [])

Creates a new FIFO cache.

Options

  • :max_bytesize - Maximum total size of all cached values (default: 2_000_000)
  • :max_value_bytesize - Maximum size of a single cached value (default: 2_000_000)

size(fifo_cache)

Returns the number of entries in the cache.