TermUI.ViewCache (TermUI v0.2.0)

View Source

View memoization cache for skipping renders when state is unchanged.

The view cache stores the last state hash and render tree for a component. When a component's state hasn't changed, we return the cached render tree instead of re-calling the view function.

Usage

cache = ViewCache.new()

# Check if view needs recalculating
case ViewCache.get(cache, state) do
  {:hit, render_tree} ->
    # Use cached result
    {render_tree, cache}

  :miss ->
    # Calculate and cache
    render_tree = Component.view(state)
    cache = ViewCache.put(cache, state, render_tree)
    {render_tree, cache}
end

Performance Considerations

State hashing uses :erlang.phash2/1 which is fast but may have collisions. For most UI state this is acceptable—the worst case is a redundant render.

Summary

Functions

Checks if the last render was slow and returns a warning if so.

Looks up a cached render tree for the given state.

Invalidates the cache, forcing next view to recalculate.

Memoizes a view function call.

Creates a new view cache.

Stores a render tree for the given state.

Records a cache hit and returns updated cache.

Records a cache miss and render time.

Returns cache statistics.

Types

render_tree()

@type render_tree() :: term()

state()

@type state() :: term()

state_hash()

@type state_hash() :: integer()

t()

@type t() :: %TermUI.ViewCache{
  hits: non_neg_integer(),
  last_render_time_us: non_neg_integer(),
  misses: non_neg_integer(),
  render_tree: render_tree() | nil,
  state_hash: state_hash() | nil
}

Functions

check_performance(arg1)

@spec check_performance(t()) :: :ok | {:slow_view, non_neg_integer()}

Checks if the last render was slow and returns a warning if so.

get(view_cache, state)

@spec get(t(), state()) :: {:hit, render_tree()} | :miss

Looks up a cached render tree for the given state.

Returns {:hit, render_tree} if state matches cache, or :miss if view needs recalculating.

invalidate(cache)

@spec invalidate(t()) :: t()

Invalidates the cache, forcing next view to recalculate.

memoize(cache, state, view_fun)

@spec memoize(t(), state(), (state() -> render_tree())) :: {render_tree(), t()}

Memoizes a view function call.

Calls the view function only if state has changed, otherwise returns cached result. Also records timing and warns about slow views.

new()

@spec new() :: t()

Creates a new view cache.

put(cache, state, render_tree)

@spec put(t(), state(), render_tree()) :: t()

Stores a render tree for the given state.

record_hit(cache)

@spec record_hit(t()) :: t()

Records a cache hit and returns updated cache.

record_miss(cache, render_time_us)

@spec record_miss(t(), non_neg_integer()) :: t()

Records a cache miss and render time.

stats(view_cache)

@spec stats(t()) :: %{
  hits: non_neg_integer(),
  misses: non_neg_integer(),
  hit_rate: float()
}

Returns cache statistics.