lru-cache vs quick-lru vs node-cache vs cache-manager vs memory-cache vs lrucache
Node.js Caching Libraries Comparison
1 Year
lru-cachequick-lrunode-cachecache-managermemory-cachelrucacheSimilar Packages:
What's Node.js Caching Libraries?

Caching libraries in Node.js are essential for optimizing application performance by storing frequently accessed data in memory. They help reduce latency and improve response times by minimizing the need to fetch data from slower sources, such as databases or APIs. Each of these libraries offers unique features and trade-offs, making them suitable for different use cases in web development.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
lru-cache187,615,0965,544820 kB11a month agoISC
quick-lru23,773,18570015.2 kB4a month agoMIT
node-cache3,265,2992,321-745 years agoMIT
cache-manager1,966,2811,79650.6 kB22 days agoMIT
memory-cache687,1861,600-328 years agoBSD-2-Clause
lrucache28,83812-08 years ago-
Feature Comparison: lru-cache vs quick-lru vs node-cache vs cache-manager vs memory-cache vs lrucache

Caching Strategy

  • lru-cache:

    lru-cache implements a Least Recently Used (LRU) caching strategy, automatically evicting the least accessed items when the cache size limit is reached. This is beneficial for applications that need to manage memory efficiently while keeping frequently accessed data readily available.

  • quick-lru:

    quick-lru is optimized for performance, focusing on speed and efficiency in managing LRU cache operations. It is ideal for high-performance applications that require rapid access to cached data.

  • node-cache:

    node-cache supports TTL (time-to-live) for cached items, allowing developers to set expiration times for each cache entry. This feature is useful for managing stale data and ensuring that the cache does not hold outdated information.

  • cache-manager:

    cache-manager provides a unified API for multiple caching stores, allowing you to switch between different backends like Redis, Memcached, or in-memory caching seamlessly. This flexibility makes it suitable for applications that may evolve in their caching needs.

  • memory-cache:

    memory-cache offers a basic caching mechanism without any specific eviction strategy, making it suitable for scenarios where you simply need to store and retrieve data quickly without worrying about memory limits or item expiration.

  • lrucache:

    lrucache also follows the LRU strategy but with a minimalistic approach, focusing on simplicity and ease of use. It is designed for developers who want a straightforward caching solution without additional features or configurations.

Performance

  • lru-cache:

    lru-cache is highly performant for in-memory caching, with low latency for get and set operations. Its automatic eviction mechanism ensures that memory usage is optimized without sacrificing access speed.

  • quick-lru:

    quick-lru is built for high performance, providing rapid access to cached items with minimal latency. It is particularly effective for applications that require quick data retrieval.

  • node-cache:

    node-cache offers good performance with the added benefit of TTL management. It balances speed with the ability to control cache expiration, making it suitable for various use cases.

  • cache-manager:

    cache-manager's performance depends on the underlying store used. While it can be efficient, the overhead of managing multiple backends may introduce some latency compared to simpler solutions. It is best used when flexibility is more important than raw speed.

  • memory-cache:

    memory-cache is simple and fast for small datasets, but it lacks advanced features like eviction policies, which may lead to performance issues as the dataset grows beyond memory limits.

  • lrucache:

    lrucache is designed for speed, providing fast access to cached items with minimal overhead. It is suitable for applications where performance is a top priority and memory usage is manageable.

Ease of Use

  • lru-cache:

    lru-cache is straightforward to implement, with a simple API that allows developers to quickly set up caching without extensive configuration. Its ease of use makes it a popular choice for many projects.

  • quick-lru:

    quick-lru is designed to be easy to use, with a clear and concise API that allows for rapid implementation of LRU caching. It is ideal for developers who want performance without complexity.

  • node-cache:

    node-cache has a simple API that allows for easy caching with TTL support. Its straightforward approach makes it accessible for developers of all skill levels.

  • cache-manager:

    cache-manager is user-friendly with a consistent API across different caching stores, making it easy to integrate and switch between various backends. However, it may require some initial setup depending on the chosen store.

  • memory-cache:

    memory-cache is very easy to use, requiring minimal setup and configuration. It is suitable for quick scripts or small applications where caching needs are basic.

  • lrucache:

    lrucache is designed for simplicity, providing a minimalistic API that is easy to understand and implement. It is ideal for developers looking for a quick caching solution without unnecessary complexity.

Memory Management

  • lru-cache:

    lru-cache automatically manages memory by evicting the least recently used items, ensuring that the cache does not exceed the specified size limit. This makes it efficient for applications with constrained memory resources.

  • quick-lru:

    quick-lru is optimized for memory management, providing efficient LRU caching with minimal overhead. It is designed for applications that require fast access to data while managing memory effectively.

  • node-cache:

    node-cache allows for TTL management, which helps control memory usage by automatically removing expired items. This feature is beneficial for maintaining a healthy memory footprint in your application.

  • cache-manager:

    cache-manager relies on the underlying store for memory management, which can vary in efficiency. It is important to choose the right store based on your application's memory requirements and performance needs.

  • memory-cache:

    memory-cache does not implement any eviction strategy, meaning it can grow indefinitely if not managed. It is best for small datasets where memory usage is not a concern.

  • lrucache:

    lrucache provides basic memory management through its LRU strategy, but it does not offer advanced features for controlling memory usage beyond eviction. It is suitable for lightweight applications.

Community and Support

  • lru-cache:

    lru-cache is widely used and has a large community, ensuring that developers can find plenty of examples and support online. Its popularity also means it is regularly maintained and updated.

  • quick-lru:

    quick-lru is relatively new compared to others, which may mean a smaller community and fewer resources. However, its performance-focused design can attract developers looking for speed.

  • node-cache:

    node-cache has a decent community and documentation, providing sufficient support for most use cases. Its straightforward nature makes it easy to troubleshoot common issues.

  • cache-manager:

    cache-manager has a strong community and is well-documented, making it easy to find support and resources. Its versatility and popularity contribute to its robustness in various applications.

  • memory-cache:

    memory-cache has a smaller community, which may limit available resources and support. However, its simplicity means that most issues can be resolved quickly without extensive documentation.

  • lrucache:

    lrucache is less popular than some alternatives, which may result in fewer community resources and support options. However, its simplicity can make it easy to troubleshoot and implement.

How to Choose: lru-cache vs quick-lru vs node-cache vs cache-manager vs memory-cache vs lrucache
  • lru-cache:

    Select lru-cache if you need a simple, efficient, and fast in-memory cache that automatically removes the least recently used items when the cache reaches its limit. It's perfect for scenarios where you want to maintain a limited amount of data in memory without complex configurations.

  • quick-lru:

    Select quick-lru if performance is a critical factor and you need a fast LRU cache implementation with minimal overhead. It's designed for high-speed operations and is ideal for applications with heavy caching demands.

  • node-cache:

    Choose node-cache if you need a straightforward caching library that provides TTL (time-to-live) support for cached items. It's useful for scenarios where you want to control the lifespan of cached data easily.

  • cache-manager:

    Choose cache-manager if you need a versatile caching solution that supports multiple stores (like memory, Redis, etc.) and requires a unified API for managing various caching strategies. It's ideal for applications that may switch between different caching backends.

  • memory-cache:

    Use memory-cache for a simple, no-frills in-memory caching solution. It's suitable for small applications or scripts where you need quick access to data without the overhead of more complex caching mechanisms.

  • lrucache:

    Opt for lrucache if you prefer a straightforward implementation of an LRU cache without additional dependencies. It offers basic functionality for managing memory usage effectively and is suitable for lightweight applications.

README for lru-cache

lru-cache

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.

Installation

npm install lru-cache --save

Usage

// hybrid module, either works
import { LRUCache } from 'lru-cache'
// or:
const { LRUCache } = require('lru-cache')
// or in minified form for web browsers:
import { LRUCache } from 'http://unpkg.com/lru-cache@9/dist/mjs/index.min.mjs'

// At least one of 'max', 'ttl', or 'maxSize' is required, to prevent
// unsafe unbounded storage.
//
// In most cases, it's best to specify a max for performance, so all
// the required memory allocation is done up-front.
//
// All the other options are optional, see the sections below for
// documentation on what each one does.  Most of them can be
// overridden for specific items in get()/set()
const options = {
  max: 500,

  // for use with tracking overall storage size
  maxSize: 5000,
  sizeCalculation: (value, key) => {
    return 1
  },

  // for use when you need to clean up something when objects
  // are evicted from the cache
  dispose: (value, key, reason) => {
    freeFromMemoryOrWhatever(value)
  },

  // for use when you need to know that an item is being inserted
  // note that this does NOT allow you to prevent the insertion,
  // it just allows you to know about it.
  onInsert: (value, key, reason) => {
    logInsertionOrWhatever(key, value)
  },

  // how long to live in ms
  ttl: 1000 * 60 * 5,

  // return stale items before removing from cache?
  allowStale: false,

  updateAgeOnGet: false,
  updateAgeOnHas: false,

  // async method to use for cache.fetch(), for
  // stale-while-revalidate type of behavior
  fetchMethod: async (
    key,
    staleValue,
    { options, signal, context }
  ) => {},
}

const cache = new LRUCache(options)

cache.set('key', 'value')
cache.get('key') // "value"

// non-string keys ARE fully supported
// but note that it must be THE SAME object, not
// just a JSON-equivalent object.
var someObject = { a: 1 }
cache.set(someObject, 'a value')
// Object keys are not toString()-ed
cache.set('[object Object]', 'a different value')
assert.equal(cache.get(someObject), 'a value')
// A similar object with same keys/values won't work,
// because it's a different object identity
assert.equal(cache.get({ a: 1 }), undefined)

cache.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

Storage Bounds Safety

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:

// a storage-unbounded ttl cache that is not an lru-cache
const cache = {
  data: new Map(),
  timers: new Map(),
  set: (k, v, ttl) => {
    if (cache.timers.has(k)) {
      clearTimeout(cache.timers.get(k))
    }
    cache.timers.set(
      k,
      setTimeout(() => cache.delete(k), ttl)
    )
    cache.data.set(k, v)
  },
  get: k => cache.data.get(k),
  has: k => cache.data.has(k),
  delete: k => {
    if (cache.timers.has(k)) {
      clearTimeout(cache.timers.get(k))
    }
    cache.timers.delete(k)
    return cache.data.delete(k)
  },
  clear: () => {
    cache.data.clear()
    for (const v of cache.timers.values()) {
      clearTimeout(v)
    }
    cache.timers.clear()
  },
}

If that isn't to your liking, check out @isaacs/ttlcache.

Storing Undefined Values

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.

cache.set(myKey, undefined)
cache.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.

import { LRUCache } from 'lru-cache'
const undefinedValue = Symbol('undefined')
const cache = new LRUCache(...)
const mySet = (key, value) =>
  cache.set(key, value === undefined ? undefinedValue : value)
const myGet = (key, value) => {
  const v = cache.get(key)
  return v === undefinedValue ? undefined : v
}

Performance

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:

const myCache = {}
const set = (k, v) => (myCache[k] = v)
const get = k => myCache[k]

set({}, 'please hang onto this for me')
set('[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:

  1. 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.

  2. Failing that, if at all possible, use short non-numeric strings (ie, less than 256 characters) as your keys, and use mnemonist's LRUCache.

  3. 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).

  4. 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.

Breaking Changes in Version 7

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.

Breaking Changes in Version 8

  • The fetchContext option was renamed to context, and may no longer be set on the cache instance itself.
  • Rewritten in TypeScript, so pretty much all the types moved around a lot.
  • The AbortController/AbortSignal polyfill was removed. For this reason, Node version 16.14.0 or higher is now required.
  • Internal properties were moved to actual private class properties.
  • Keys and values must not be null or undefined.
  • Minified export available at 'lru-cache/min', for both CJS and MJS builds.

Breaking Changes in Version 9

  • Named export only, no default export.
  • AbortController polyfill returned, albeit with a warning when used.

Breaking Changes in Version 10

  • 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.