Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Memoize functions - an optimization technique used to speed up consecutive function calls by caching the result of calls with identical input

License

NotificationsYou must be signed in to change notification settings

sindresorhus/memoize

Memoize functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input

Memory is automatically released when an item expires or the cache is cleared.

By default,only the first argument is considered and it only works withprimitives. If you need to cache multiple arguments or cacheobjectsby value, have a look at alternativecaching strategies below.

Install

$ npm install mem

Usage

constmem=require('mem');leti=0;constcounter=()=>++i;constmemoized=mem(counter);memoized('foo');//=> 1// Cached as it's the same argumentmemoized('foo');//=> 1// Not cached anymore as the argument changedmemoized('bar');//=> 2memoized('bar');//=> 2// Only the first argument is considered by defaultmemoized('bar','foo');//=> 2
Works fine with promise returning functions
constmem=require('mem');leti=0;constcounter=async()=>++i;constmemoized=mem(counter);(async()=>{console.log(awaitmemoized());//=> 1// The return value didn't increase as it's cachedconsole.log(awaitmemoized());//=> 1})();
constmem=require('mem');constgot=require('got');constdelay=require('delay');constmemGot=mem(got,{maxAge:1000});(async()=>{awaitmemGot('https://sindresorhus.com');// This call is cachedawaitmemGot('https://sindresorhus.com');awaitdelay(2000);// This call is not cached as the cache has expiredawaitmemGot('https://sindresorhus.com');})();

Caching strategy

By default, only the first argument is compared via exact equality (===) to determine whether a call is identical.

constpower=mem((a,b)=>Math.power(a,b));power(2,2);// => 4, stored in cache with the key 2 (number)power(2,3);// => 4, retrieved from cache at key 2 (number), it's wrong

You will have to use thecache andcacheKey options appropriate to your function. In this specific case, the following could work:

constpower=mem((a,b)=>Math.power(a,b),{cacheKey:arguments_=>arguments_.join(',')});power(2,2);// => 4, stored in cache with the key '2,2' (both arguments as one string)power(2,3);// => 8, stored in cache with the key '2,3'

More advanced examples follow.

Example: Options-like argument

If your function accepts an object, it won't be memoized out of the box:

constheavyMemoizedOperation=mem(heavyOperation);heavyMemoizedOperation({full:true});// Stored in cache with the object as keyheavyMemoizedOperation({full:true});// Stored in cache with the object as key, again// The objects look the same but for JS they're two different objects

You might want to serialize or hash them, for example usingJSON.stringify or something likeserialize-javascript, which can also serializeRegExp,Date and so on.

constheavyMemoizedOperation=mem(heavyOperation,{cacheKey:JSON.stringify});heavyMemoizedOperation({full:true});// Stored in cache with the key '[{"full":true}]' (string)heavyMemoizedOperation({full:true});// Retrieved from cache

The same solution also works if it accepts multiple serializable objects:

constheavyMemoizedOperation=mem(heavyOperation,{cacheKey:JSON.stringify});heavyMemoizedOperation('hello',{full:true});// Stored in cache with the key '["hello",{"full":true}]' (string)heavyMemoizedOperation('hello',{full:true});// Retrieved from cache

Example: Multiple non-serializable arguments

If your function accepts multiple arguments that aren't supported byJSON.stringify (e.g. DOM elements and functions), you can instead extend the initial exact equality (===) to work on multiple arguments usingmany-keys-map:

constManyKeysMap=require('many-keys-map');constaddListener=(emitter,eventName,listener)=>emitter.on(eventName,listener);constaddOneListener=mem(addListener,{cacheKey:arguments_=>arguments_,// Use *all* the arguments as keycache:newManyKeysMap()// Correctly handles all the arguments for exact equality});addOneListener(header,'click',console.log);// `addListener` is run, and it's cached with the `arguments` array as keyaddOneListener(header,'click',console.log);// `addListener` is not run againaddOneListener(mainContent,'load',console.log);// `addListener` is run, and it's cached with the `arguments` array as key

Better yet, if your function’s arguments are compatible withWeakMap, you should usedeep-weak-map instead ofmany-keys-map. This will help avoid memory leaks.

API

mem(fn, options?)

fn

Type:Function

Function to be memoized.

options

Type:object

maxAge

Type:number
Default:Infinity

Milliseconds until the cache expires.

cacheKey

Type:Function
Default:arguments_ => arguments_[0]
Example:arguments_ => JSON.stringify(arguments_)

Determines the cache key for storing the result based on the function arguments. By default,only the first argument is considered.

AcacheKey function can return any type supported byMap (or whatever structure you use in thecache option).

Refer to thecaching strategies section for more information.

cache

Type:object
Default:new Map()

Use a different cache storage. Must implement the following methods:.has(key),.get(key),.set(key, value),.delete(key), and optionally.clear(). You could for example use aWeakMap instead orquick-lru for a LRU cache.

Refer to thecaching strategies section for more information.

mem.clear(fn)

Clear all cached data of a memoized function.

fn

Type:Function

Memoized function.

Tips

Cache statistics

If you want to know how many times your cache had a hit or a miss, you can make use ofstats-map as a replacement for the default cache.

Example

constmem=require('mem');constStatsMap=require('stats-map');constgot=require('got');constcache=newStatsMap();constmemGot=mem(got,{cache});(async()=>{awaitmemGot('https://sindresorhus.com');awaitmemGot('https://sindresorhus.com');awaitmemGot('https://sindresorhus.com');console.log(cache.stats);//=> {hits: 2, misses: 1}})();

Related

  • p-memoize - Memoize promise-returning & async functions

Get professional support for this package with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.

About

Memoize functions - an optimization technique used to speed up consecutive function calls by caching the result of calls with identical input

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Sponsor this project

  •  
  •  

Packages

No packages published

Contributors18


[8]ページ先頭

©2009-2025 Movatter.jp