A GC-aware cache using WeakRef and FinalizationRegistry
npm install smart-cache-gcSmartCache is a memory-efficient in-memory cache built with WeakRef and FinalizationRegistry. It automatically cleans up values when they are garbage collected, helping you avoid memory leaks in high-uptime applications like servers, data processors, or editor tools.
WeakRef and FinalizationRegistry
.get(), .has(), .delete(), .clear(), .keys(), .size
maxSize support with LRU eviction strategy
npm install smart-cache-gc
`
> SmartCache works out of the box with optional ttl and maxSize for expiration and LRU eviction.
๐ ๏ธ Usage
`
import { SmartCache } from 'smart-cache-gc'
// Optional TTL and maxSize support
const cacheWithOptions = new SmartCache`
๐ Examples
For comprehensive examples and real-world use cases, check out the examples directory in this repository:
Basic Usage - Getting started with SmartCache
Advanced Configuration - Complex scenarios and best practices
Performance Benchmarks - Testing memory efficiency
๐ GC Cleanup Hook
You can register a cleanup callback for when an object is garbage collected:
`
cache.getNotificationOnGC({
key,
value: yourObject,
cleanup: (key, value) => {
console.log(${String(key)} was garbage collected)
}
})
`
๐งช Testing
`
node --expose-gc node_modules/vitest/vitest.mjs run
`
๐ Methods
| Method | Description |
| --------------------- | -------------------------------------------- |
| set(key, value) | Store a value under a key (object or symbol) |
| get(key) | Get cached value or null if GC'd |
| has(key) | Returns true if value is alive |
| delete(key) | Removes an entry |
| clear() | Clears all entries |
| keys() | Returns all alive keys |
| size (getter) | Number of alive entries |
| getNotificationOnGC | Register a GC cleanup callback for a value |
โ๏ธ Constructor Options
| Option | Description |
| ------------ | ---------------------------------------------- |
| defaultTtl | Default time-to-live for entries (in ms) |
| maxSize | Maximum number of live entries before eviction |
๐ ttl per-entry (override)
You can override the default TTL on a per-entry basis using the optional ttl in .set():
`
cache.set(key, value, { ttl: 5000 }) // expires in 5 seconds
`
This overrides the defaultTtl set in the constructor (if any) for this specific entry only.
โป๏ธ LRU Eviction
When maxSize is defined, SmartCache uses an optimized LRU eviction policy to remove the least recently accessed entries. This keeps memory usage predictable in high-load scenarios.
Support
> โ ๏ธ This package requires support for WeakRef and FinalizationRegistry`. These are available in: