Raxol. Performance. Cache
(Raxol v2.6.0)
View Source
Cache behavior and utilities for Raxol performance optimization.
This module defines the standard cache interface and provides utilities for cache key generation and invalidation patterns.
Caching Strategies
Raxol uses several caching strategies depending on the use case:
ETS Cache (ETSCacheManager)
For runtime caching with LRU eviction. Best for:
- Layout calculations
- Style resolutions
- Buffer regions
- Cell creation
Module Attribute Cache
Compile-time caching using module attributes. Best for:
- Static ANSI sequences
- Predefined color maps
- Constants
Delegated Cache
Using cache: true options on existing modules. Best for:
- Theme resolution
- Component styles
Cache Keys
Cache keys should be deterministic and based on the input parameters.
Use compute_hash/1 for complex structures.
Example Usage
# Using ETSCacheManager directly
alias Raxol.Performance.ETSCacheManager
case ETSCacheManager.get_layout(tree_hash, constraints) do
{:ok, result} -> result
:miss ->
result = compute_expensive_layout(tree, constraints)
ETSCacheManager.cache_layout(tree_hash, constraints, result)
result
end
# Using the cache pattern helpers
alias Raxol.Performance.Cache
Cache.with_cache(
:layout,
{tree_hash, constraints},
fn -> compute_expensive_layout(tree, constraints) end
)
Summary
Functions
Clears the specified cache.
Clears all caches.
Computes a deterministic hash for a complex structure.
Computes a hash suitable for use as a cache key, including structure type.
Gets a value from the specified cache.
Puts a value into the specified cache.
Gets statistics for all caches.
Wraps a computation with caching.
Types
Functions
@spec clear(cache_name()) :: :ok
Clears the specified cache.
@spec clear_all() :: :ok
Clears all caches.
@spec compute_hash(term()) :: non_neg_integer()
Computes a deterministic hash for a complex structure.
Use this for generating cache keys from complex data structures.
@spec compute_typed_hash(atom(), term()) :: {atom(), non_neg_integer()}
Computes a hash suitable for use as a cache key, including structure type.
Returns {type, hash} tuple for more specific cache key matching.
@spec get(cache_name(), cache_key()) :: cache_result()
Gets a value from the specified cache.
@spec put(cache_name(), cache_key(), term()) :: term()
Puts a value into the specified cache.
@spec stats() :: map()
Gets statistics for all caches.
@spec with_cache(cache_name(), cache_key(), (-> term()), keyword()) :: term()
Wraps a computation with caching.
If the value exists in cache, returns it. Otherwise, computes the value, caches it, and returns it.
Options
:ttl- Time to live in milliseconds (not implemented, for future use)
Examples
Cache.with_cache(:layout, {tree, constraints}, fn ->
expensive_layout_computation(tree, constraints)
end)