@se-oss/lru is a feature-rich LRU cache engineered for high performance, offering excellent throughput on par with industry-standard libraries. It is designed for modern applications that require efficient caching with advanced features like TTL, size-based eviction, and asynchronous fetching.
npm install @se-oss/lruInstall using your favorite package manager
pnpm
pnpm install @se-oss/lruyarn
yarn add @se-oss/lru@se-oss/lru is a powerful and easy-to-use LRU cache for Node.js and the browser. Hereβs a quick example to get you started:
import { LRUCache } from '@se-oss/lru';
// Create a cache with a max of 100 items and a 5-minute TTL
const cache = new LRUCache<string, number>({
max: 100,
ttl: 1000 * 60 * 5, // 5 minutes
});
// Set some values
cache.set('key1', 123);
cache.set('key2', 456);
// Get a value
console.log(cache.get('key1')); // 123
// Check if a key exists
console.log(cache.has('key2')); // true
// Delete a key
cache.delete('key1');
console.log(cache.has('key1')); // false
// The cache will automatically evict the least recently used items
// and expire items based on the TTL.import { LRUCache } from '@se-oss/lru';
const cache = new LRUCache<string, string>({
max: 100,
ttl: 1000 * 60 * 5, // 5 minutes
});
cache.set('session', 'user-session-data');
// The item will automatically expire after 5 minutesThe fetch method allows you to transparently handle cache misses by fetching data from an external source.
import { LRUCache } from '@se-oss/lru';
const cache = new LRUCache<string, any>({
max: 100,
fetchMethod: async (key) => {
console.log(`Fetching ${key} from API...`);
const response = await fetch(`https://api.example.com/data/${key}`);
return response.json();
},
});
async function getData(key: string) {
const data = await cache.fetch(key);
console.log(data);
}
getData('user-profile'); // Fetches from API
getData('user-profile'); // Returns from cacheFor all configuration options, please see the API docs.
| Library | SET ops/sec | GET ops/sec | UPDATE ops/sec | DELETE ops/sec |
|---|---|---|---|---|
| @se-oss/lru | 8,283,012 | 17,011,923 | 15,848,670 | 31,051,192 |
| tiny-lru | 3,804,727 | 27,954,423 | 26,658,547 | 18,273,447 |
| lru-cache | 9,466,302 | 17,964,613 | 17,062,288 | 30,668,986 |
| quick-lru | 14,928,443 | 10,391,375 | 15,257,320 | 26,669,894 |
Benchmark script: src/index.bench.ts
Note on tiny-lru: The impressive GET and UPDATE performance of tiny-lru is largely due to its minimalist design. It is a raw LRU implementation and lacks many of the advanced features (like fetch, size-based eviction, and detailed callbacks) found in @se-oss/lru and lru-cache. This results in lower overhead for basic operations.
Want to contribute? Awesome! To show your support is to star the project, or to raise issues on GitHub
Thanks again for your support, it is much appreciated! π
MIT Β© Shahrad Elahi and contributors.