TermUI.ViewCache (TermUI v0.2.0)
View SourceView 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}
endPerformance 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
@type render_tree() :: term()
@type state() :: term()
@type state_hash() :: integer()
@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
@spec check_performance(t()) :: :ok | {:slow_view, non_neg_integer()}
Checks if the last render was slow and returns a warning if so.
@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.
Invalidates the cache, forcing next view to recalculate.
@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.
@spec new() :: t()
Creates a new view cache.
@spec put(t(), state(), render_tree()) :: t()
Stores a render tree for the given state.
Records a cache hit and returns updated cache.
@spec record_miss(t(), non_neg_integer()) :: t()
Records a cache miss and render time.
@spec stats(t()) :: %{ hits: non_neg_integer(), misses: non_neg_integer(), hit_rate: float() }
Returns cache statistics.