Performance
Defers the first call until it is actually invoked. Subsequent calls execute normally without caching.
Performance
Performance decorators reduce redundant work, bound resource usage, and optimize execution. Use them to cache results, batch calls, limit rates, and compress payloads.
lazy
What it is
Defers the first call until it is actually invoked. Subsequent calls execute normally without caching.
When to use it
- Optional initialization
- Resources that may never be needed
Async / sync support
Func<R> | Func1<T, R> | Func2<T1, T2, R> | FuncSync<R> |
|---|---|---|---|
| ✅ | ✅ | ✅ | ❌ |
API reference
| |
Examples
Minimal
| |
Real world
| |
Best practices
- Combine with
onceif the result should be cached forever. - Combine with
memoizeif results should be cached per argument.
Common pitfalls
lazydoes not cache the result; it only delays the first execution.
warmUp
What it is
Pre-executes a function and optionally refreshes the cached result on a timer.
When to use it
- Keeping a fresh cache ready before the first user request
- Background refresh of expensive data
Async / sync support
Func<R> | Func1<T, R> | Func2<T1, T2, R> | FuncSync<R> |
|---|---|---|---|
| ✅ | ✅ | ✅ | ❌ |
API reference
| |
For Func1/Func2:
| |
WarmUpTrigger:
onInit— warm up when the decorator is created.onFirstCall— warm up on the first call.manual— warm up only when requested.
Methods:
triggerWarmUp()— arity 0 only.warmUpWith(T arg)/warmUpWith(T1 arg1, T2 arg2)— arity 1/2.dispose()— cancels the refresh timer.
Examples
Minimal
| |
Real world
| |
Best practices
- Always call
dispose()when the warm-up decorator is no longer needed. - Use
keepFreshonly for data that is safe to refresh in the background.
Common pitfalls
- Arity 0 defaults to
onInit; arity 1/2 default tomanual. - Background refresh errors are silently ignored.
batch
What it is
Accumulates calls and executes them together in a single batch.
When to use it
- Batching database writes
- Bulk API calls
- Coalescing small operations
Async / sync support
Func<R> | Func1<T, R> | Func2<T1, T2, R> | FuncSync<R> |
|---|---|---|---|
| ❌ | ✅ | ✅ | ❌ |
API reference
| |
executor— processes the accumulated list and returns a single result distributed to all pending calls.maxSize— flush when the batch reaches this size.maxWait— flush after this duration even ifmaxSizeis not reached.
Methods:
flush()— execute the current batch immediately.cancel()— complete pending calls withStateError.
Examples
Minimal
| |
Real world
| |
Best practices
- Set
maxWaitto bound latency. - Make the executor idempotent in case of partial failures.
Common pitfalls
batchis only available onFunc1andFunc2.- All pending calls receive the same result from the executor.
cacheAside
What it is
Cache-aside pattern with TTL and refresh strategies. Reads from a cache first; on miss, populates the cache and returns the result.
When to use it
- Read-through caching
- Reducing database or API load
Async / sync support
Func<R> | Func1<T, R> | Func2<T1, T2, R> | FuncSync<R> |
|---|---|---|---|
| ❌ | ✅ | ✅ | ❌ |
API reference
| |
RefreshStrategy:
nonebackgroundRefreshrefreshOnAccess
Built-in InMemoryCache<K, V>.
Methods:
invalidate(T arg)/invalidate(T1 arg1, T2 arg2)clearCache()
Examples
Minimal
| |
Real world
| |
Best practices
- Set a TTL to avoid serving stale data forever.
- Use
backgroundRefreshfor frequently accessed, non-critical data.
Common pitfalls
cacheAsideis only available onFunc1andFunc2.- Cache keys must have stable
==andhashCode.
priorityQueue
What it is
Priority-ordered execution with optional max queue size, max concurrency, and starvation prevention.
When to use it
- Task queues where some items are more important
- Preventing low-priority tasks from starving
Async / sync support
Func<R> | Func1<T, R> | Func2<T1, T2, R> | FuncSync<R> |
|---|---|---|---|
| ❌ | ✅ | ✅ | ❌ |
API reference
| |
QueueFullPolicy:
dropLowestPrioritydropNewerrorwaitForSpace
Properties:
queueLengthactiveCount
Examples
Minimal
| |
Real world
| |
Best practices
- Set
maxConcurrent> 1 for I/O-bound work. - Monitor
activeCountandqueueLengthfor overload.
Common pitfalls
priorityQueueis only available onFunc1andFunc2.dropLowestPriorityevicts the least important queued item, not the running one.
rateLimit
What it is
Limits how many calls can be made within a time window using token bucket, leaky bucket, fixed window, or sliding window algorithms.
When to use it
- API client rate limiting
- Protecting downstream services
- Fair resource sharing
Async / sync support
Func<R> | Func1<T, R> | Func2<T1, T2, R> | FuncSync<R> |
|---|---|---|---|
| ✅ | ✅ | ✅ | ❌ |
API reference
| |
RateLimitStrategy:
tokenBucketleakyBucketfixedWindowslidingWindow
Methods:
reset()dispose()— cancels the leaky-bucket timer.
Examples
Minimal
| |
Real world
| |
Best practices
- Choose
slidingWindowfor accuracy,tokenBucketfor burst tolerance. - Call
dispose()when the rate limiter is no longer needed.
Common pitfalls
- Exceeding the limit throws
StateError. leakyBucketuses a periodic timer; remember todispose().
memoize
What it is
Caches results by argument with TTL, max size, and eviction policy (LRU, LFU, FIFO).
When to use it
- Expensive pure functions
- Repeated lookups with the same inputs
Async / sync support
Func<R> | Func1<T, R> | Func2<T1, T2, R> | FuncSync<R> |
|---|---|---|---|
| ✅ | ✅ | ✅ | ❌ |
API reference
| |
EvictionPolicy:
lru— least recently usedlfu— least frequently usedfifo— first in, first out
Methods:
clear()— clear all cached results.clearArg(arg)/clearArgs(arg1, arg2)— remove a specific entry (arity 1/2).
Examples
Minimal
| |
Real world
| |
Best practices
- Set
ttlfor data that can become stale. - Use
lrufor general caching; uselfufor hot-key workloads.
Common pitfalls
- Memoization keys use the argument’s
==andhashCode. - Errors are cached too unless cleared.
deduplicate
What it is
Suppresses duplicate calls within a time window, returning the previous result for repeated arguments.
When to use it
- Preventing duplicate network requests
- Coalescing identical user actions
Async / sync support
Func<R> | Func1<T, R> | Func2<T1, T2, R> | FuncSync<R> |
|---|---|---|---|
| ✅ | ✅ | ✅ | ❌ |
API reference
| |
Methods:
reset()— clear deduplication state.resetArg(arg)/resetArgs(arg1, arg2)— reset a specific entry (arity 1/2).
Examples
Minimal
| |
Real world
| |
Best practices
- Set a
windowthat matches the expected duplicate rate. - Reset after a known state change.
Common pitfalls
- Without a
window, deduplication behavior depends on the implementation’s default. - Concurrent duplicate calls share the in-flight result.
share
What it is
Shares a single in-flight execution among concurrent callers with the same arguments.
When to use it
- Thundering-herd protection
- Expensive operations started by many callers at once
Async / sync support
Func<R> | Func1<T, R> | Func2<T1, T2, R> | FuncSync<R> |
|---|---|---|---|
| ✅ | ✅ | ✅ | ❌ |
API reference
| |
Examples
Minimal
| |
Real world
| |
Best practices
- Use
sharefor expensive, idempotent reads. - Combine with
memoizeif the result should be retained after completion.
Common pitfalls
- Errors are shared too; all concurrent callers receive the same exception.
- Does not cache results after completion unless paired with
memoize.
compress
What it is
Compresses or decompresses string and byte data before passing it to the function.
When to use it
- Reducing payload size for network or storage
- Working with
Uint8Listor base64 strings
Async / sync support
Func<R> | Func1<String, R> | Func1<Uint8List, R> | FuncSync<R> |
|---|---|---|---|
| ✅ decompress | ✅ compress | ✅ compressBytes | ❌ |
API reference
| |
CompressionAlgorithm:
gzipzlib
CompressionLevel:
nonefastbalancedbest
Examples
Minimal
| |
Real world
| |
Best practices
- Set
thresholdso small payloads are not compressed unnecessarily. - Match the algorithm between compression and decompression.
Common pitfalls
compressis only forFunc1<String, R>;compressBytesis forFunc1<Uint8List, R>.- Decompressing corrupt data throws a format exception.
once
What it is
Executes the function once and permanently caches the result (or error). Optional resetOn predicate allows retry for matching errors.
When to use it
- One-time initialization
- Singleton creation
- Expensive setup that must not repeat
Async / sync support
Func<R> | Func1<T, R> | Func2<T1, T2, R> | FuncSync<R> |
|---|---|---|---|
| ✅ | ✅ | ✅ | ❌ |
API reference
| |
Methods:
reset()— reset arity-0 state.reset([T arg])/reset([T1 arg1, T2 arg2])— reset a specific entry.
Examples
Minimal
| |
Real world
| |
Best practices
- Use
resetOnonly for recoverable initialization errors. - Call
reset()after a known invalidation event.
Common pitfalls
- If the first call fails, the error is cached forever unless
resetOnmatches. onceis not appropriate for functions whose inputs change frequently.