Gathering detailed insights and metrics for lru-cache
Gathering detailed insights and metrics for lru-cache
Gathering detailed insights and metrics for lru-cache
Gathering detailed insights and metrics for lru-cache
A fast cache that automatically deletes the least recently used items
npm install lru-cache
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
5,375 Stars
510 Commits
353 Forks
52 Watching
43 Branches
46 Contributors
Updated on 27 Nov 2024
Minified
Minified + Gzipped
TypeScript (74.33%)
JavaScript (24.49%)
Shell (1.08%)
Makefile (0.11%)
Cumulative downloads
Total Downloads
Last day
-6.1%
35,881,867
Compared to previous day
Last week
2.3%
209,353,514
Compared to previous week
Last month
11.3%
858,668,917
Compared to previous month
Last year
37.8%
9,488,562,953
Compared to previous year
A cache object that deletes the least-recently-used items.
Specify a max number of the most recently used items that you want to keep, and this cache will keep that many of the most recently accessed items.
This is not primarily a TTL cache, and does not make strong TTL
guarantees. There is no preemptive pruning of expired items by
default, but you may set a TTL on the cache or on a single
set
. If you do so, it will treat expired items as missing, and
delete them when fetched. If you are more interested in TTL
caching than LRU caching, check out
@isaacs/ttlcache.
As of version 7, this is one of the most performant LRU implementations available in JavaScript, and supports a wide diversity of use cases. However, note that using some of the features will necessarily impact performance, by causing the cache to have to do more work. See the "Performance" section below.
1npm install lru-cache --save
1// hybrid module, either works 2import { LRUCache } from 'lru-cache' 3// or: 4const { LRUCache } = require('lru-cache') 5// or in minified form for web browsers: 6import { LRUCache } from 'http://unpkg.com/lru-cache@9/dist/mjs/index.min.mjs' 7 8// At least one of 'max', 'ttl', or 'maxSize' is required, to prevent 9// unsafe unbounded storage. 10// 11// In most cases, it's best to specify a max for performance, so all 12// the required memory allocation is done up-front. 13// 14// All the other options are optional, see the sections below for 15// documentation on what each one does. Most of them can be 16// overridden for specific items in get()/set() 17const options = { 18 max: 500, 19 20 // for use with tracking overall storage size 21 maxSize: 5000, 22 sizeCalculation: (value, key) => { 23 return 1 24 }, 25 26 // for use when you need to clean up something when objects 27 // are evicted from the cache 28 dispose: (value, key) => { 29 freeFromMemoryOrWhatever(value) 30 }, 31 32 // how long to live in ms 33 ttl: 1000 * 60 * 5, 34 35 // return stale items before removing from cache? 36 allowStale: false, 37 38 updateAgeOnGet: false, 39 updateAgeOnHas: false, 40 41 // async method to use for cache.fetch(), for 42 // stale-while-revalidate type of behavior 43 fetchMethod: async ( 44 key, 45 staleValue, 46 { options, signal, context } 47 ) => {}, 48} 49 50const cache = new LRUCache(options) 51 52cache.set('key', 'value') 53cache.get('key') // "value" 54 55// non-string keys ARE fully supported 56// but note that it must be THE SAME object, not 57// just a JSON-equivalent object. 58var someObject = { a: 1 } 59cache.set(someObject, 'a value') 60// Object keys are not toString()-ed 61cache.set('[object Object]', 'a different value') 62assert.equal(cache.get(someObject), 'a value') 63// A similar object with same keys/values won't work, 64// because it's a different object identity 65assert.equal(cache.get({ a: 1 }), undefined) 66 67cache.clear() // empty the cache
If you put more stuff in the cache, then less recently used items will fall out. That's what an LRU cache is.
For full description of the API and all options, please see the LRUCache typedocs
This implementation aims to be as flexible as possible, within the limits of safe memory consumption and optimal performance.
At initial object creation, storage is allocated for max
items.
If max
is set to zero, then some performance is lost, and item
count is unbounded. Either maxSize
or ttl
must be set if
max
is not specified.
If maxSize
is set, then this creates a safe limit on the
maximum storage consumed, but without the performance benefits of
pre-allocation. When maxSize
is set, every item must provide
a size, either via the sizeCalculation
method provided to the
constructor, or via a size
or sizeCalculation
option provided
to cache.set()
. The size of every item must be a positive
integer.
If neither max
nor maxSize
are set, then ttl
tracking must
be enabled. Note that, even when tracking item ttl
, items are
not preemptively deleted when they become stale, unless
ttlAutopurge
is enabled. Instead, they are only purged the
next time the key is requested. Thus, if ttlAutopurge
, max
,
and maxSize
are all not set, then the cache will potentially
grow unbounded.
In this case, a warning is printed to standard error. Future
versions may require the use of ttlAutopurge
if max
and
maxSize
are not specified.
If you truly wish to use a cache that is bound only by TTL
expiration, consider using a Map
object, and calling
setTimeout
to delete entries when they expire. It will perform
much better than an LRU cache.
Here is an implementation you may use, under the same license as this package:
1// a storage-unbounded ttl cache that is not an lru-cache 2const cache = { 3 data: new Map(), 4 timers: new Map(), 5 set: (k, v, ttl) => { 6 if (cache.timers.has(k)) { 7 clearTimeout(cache.timers.get(k)) 8 } 9 cache.timers.set( 10 k, 11 setTimeout(() => cache.delete(k), ttl) 12 ) 13 cache.data.set(k, v) 14 }, 15 get: k => cache.data.get(k), 16 has: k => cache.data.has(k), 17 delete: k => { 18 if (cache.timers.has(k)) { 19 clearTimeout(cache.timers.get(k)) 20 } 21 cache.timers.delete(k) 22 return cache.data.delete(k) 23 }, 24 clear: () => { 25 cache.data.clear() 26 for (const v of cache.timers.values()) { 27 clearTimeout(v) 28 } 29 cache.timers.clear() 30 }, 31}
If that isn't to your liking, check out @isaacs/ttlcache.
This cache never stores undefined values, as undefined
is used
internally in a few places to indicate that a key is not in the
cache.
You may call cache.set(key, undefined)
, but this is just
an alias for cache.delete(key)
. Note that this has the effect
that cache.has(key)
will return false after setting it to
undefined.
1cache.set(myKey, undefined) 2cache.has(myKey) // false!
If you need to track undefined
values, and still note that the
key is in the cache, an easy workaround is to use a sigil object
of your own.
1import { LRUCache } from 'lru-cache' 2const undefinedValue = Symbol('undefined') 3const cache = new LRUCache(...) 4const mySet = (key, value) => 5 cache.set(key, value === undefined ? undefinedValue : value) 6const myGet = (key, value) => { 7 const v = cache.get(key) 8 return v === undefinedValue ? undefined : v 9}
As of January 2022, version 7 of this library is one of the most performant LRU cache implementations in JavaScript.
Benchmarks can be extremely difficult to get right. In particular, the performance of set/get/delete operations on objects will vary wildly depending on the type of key used. V8 is highly optimized for objects with keys that are short strings, especially integer numeric strings. Thus any benchmark which tests solely using numbers as keys will tend to find that an object-based approach performs the best.
Note that coercing anything to strings to use as object keys is unsafe, unless you can be 100% certain that no other type of value will be used. For example:
1const myCache = {} 2const set = (k, v) => (myCache[k] = v) 3const get = k => myCache[k] 4 5set({}, 'please hang onto this for me') 6set('[object Object]', 'oopsie')
Also beware of "Just So" stories regarding performance. Garbage collection of large (especially: deep) object graphs can be incredibly costly, with several "tipping points" where it increases exponentially. As a result, putting that off until later can make it much worse, and less predictable. If a library performs well, but only in a scenario where the object graph is kept shallow, then that won't help you if you are using large objects as keys.
In general, when attempting to use a library to improve performance (such as a cache like this one), it's best to choose an option that will perform well in the sorts of scenarios where you'll actually use it.
This library is optimized for repeated gets and minimizing eviction time, since that is the expected need of a LRU. Set operations are somewhat slower on average than a few other options, in part because of that optimization. It is assumed that you'll be caching some costly operation, ideally as rarely as possible, so optimizing set over get would be unwise.
If performance matters to you:
If it's at all possible to use small integer values as keys, and you can guarantee that no other types of values will be used as keys, then do that, and use a cache such as lru-fast, or mnemonist's LRUCache which uses an Object as its data store.
Failing that, if at all possible, use short non-numeric strings (ie, less than 256 characters) as your keys, and use mnemonist's LRUCache.
If the types of your keys will be anything else, especially long strings, strings that look like floats, objects, or some mix of types, or if you aren't sure, then this library will work well for you.
If you do not need the features that this library provides (like asynchronous fetching, a variety of TTL staleness options, and so on), then mnemonist's LRUMap is a very good option, and just slightly faster than this module (since it does considerably less).
Do not use a dispose
function, size tracking, or especially
ttl behavior, unless absolutely needed. These features are
convenient, and necessary in some use cases, and every attempt
has been made to make the performance impact minimal, but it
isn't nothing.
This library changed to a different algorithm and internal data structure in version 7, yielding significantly better performance, albeit with some subtle changes as a result.
If you were relying on the internals of LRUCache in version 6 or before, it probably will not work in version 7 and above.
fetchContext
option was renamed to context
, and may no
longer be set on the cache instance itself.null
or undefined
.'lru-cache/min'
, for both CJS
and MJS builds.cache.fetch()
return type is now Promise<V | undefined>
instead of Promise<V | void>
. This is an irrelevant change
practically speaking, but can require changes for TypeScript
users.For more info, see the change log.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
1 existing vulnerabilities detected
Details
Reason
4 commit(s) and 4 issue activity found in the last 90 days -- score normalized to 6
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
Found 1/30 approved changesets -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More