micro-memoize

A tiny, crazy fast memoization library for the 95% use-case

README

micro-memoize


A tiny, crazy fast memoization library for the 95% use-case

Summary


As the author of [moize](https://github.com/planttheidea/moize), I created a consistently fast memoization library, but moize has a lot of features to satisfy a large number of edge cases. micro-memoize is a simpler approach, focusing on the core feature set with a much smaller footprint (~1.44kB minified+gzipped). Stripping out these edge cases also allows micro-memoize to be faster across the board than moize.

Importing


ESM in browsers:

  1. ```ts
  2. import memoize from 'micro-memoize';
  3. ```

ESM in NodeJS:

  1. ```ts
  2. import memoize from 'micro-memoize/mjs';
  3. ```

CommonJS:

  1. ```ts
  2. const memoize = require('micro-memoize');
  3. ```

Usage


  1. ```ts
  2. const assembleToObject = (one: string, two: string) => ({ one, two });

  3. const memoized = memoize(assembleToObject);

  4. console.log(memoized('one', 'two')); // {one: 'one', two: 'two'}
  5. console.log(memoized('one', 'two')); // pulled from cache, {one: 'one', two: 'two'}
  6. ```

Types


If you need them, all types are available under the MicroMemoize namespace.

  1. ```ts
  2. import { MicroMemoize } from 'micro-memoize';
  3. ```

Composition


Starting in 4.0.0, you can compose memoized functions if you want to have multiple types of memoized versions based on different options.

  1. ```ts
  2. const simple = memoized(fn); // { maxSize: 1 }
  3. const upToFive = memoized(simple, { maxSize: 5 }); // { maxSize: 5 }
  4. const withCustomEquals = memoized(upToFive, { isEqual: deepEqual }); // { maxSize: 5, isEqual: deepEqual }
  5. ```

NOTE: The original function is the function used in the composition, the composition only applies to the options. In the example above, upToFive does not call simple, it calls fn.

Options


isEqual


function(object1: any, object2: any): boolean, _defaults to isSameValueZero_

Custom method to compare equality of keys, determining whether to pull from cache or not, by comparing each argument in order.

Common use-cases:

- Deep equality comparison
- Limiting the arguments compared

  1. ```ts
  2. import { deepEqual } from 'fast-equals';

  3. type ContrivedObject = {
  4.   deep: string;
  5. };

  6. const deepObject = (object: {
  7.   foo: ContrivedObject;
  8.   bar: ContrivedObject;
  9. }) => ({
  10.   foo: object.foo,
  11.   bar: object.bar,
  12. });

  13. const memoizedDeepObject = memoize(deepObject, { isEqual: deepEqual });

  14. console.log(
  15.   memoizedDeepObject({
  16.     foo: {
  17.       deep: 'foo',
  18.     },
  19.     bar: {
  20.       deep: 'bar',
  21.     },
  22.     baz: {
  23.       deep: 'baz',
  24.     },
  25.   }),
  26. ); // {foo: {deep: 'foo'}, bar: {deep: 'bar'}}

  27. console.log(
  28.   memoizedDeepObject({
  29.     foo: {
  30.       deep: 'foo',
  31.     },
  32.     bar: {
  33.       deep: 'bar',
  34.     },
  35.     baz: {
  36.       deep: 'baz',
  37.     },
  38.   }),
  39. ); // pulled from cache
  40. ```

NOTE: The default method tests for SameValueZero equality, which is summarized as strictly equal while also consideringNaN equal to NaN.

isMatchingKey


function(object1: any[], object2: any[]): boolean

Custom method to compare equality of keys, determining whether to pull from cache or not, by comparing the entire key.

Common use-cases:

- Comparing the shape of the key
- Matching on values regardless of order
- Serialization of arguments

  1. ```ts
  2. import { deepEqual } from 'fast-equals';

  3. type ContrivedObject = { foo: string; bar: number };

  4. const deepObject = (object: ContrivedObject) => ({
  5.   foo: object.foo,
  6.   bar: object.bar,
  7. });

  8. const memoizedShape = memoize(deepObject, {
  9.   // receives the full key in cache and the full key of the most recent call
  10.   isMatchingKey(key1, key2) {
  11.     const object1 = key1[0];
  12.     const object2 = key2[0];

  13.     return (
  14.       object1.hasOwnProperty('foo') &&
  15.       object2.hasOwnProperty('foo') &&
  16.       object1.bar === object2.bar
  17.     );
  18.   },
  19. });

  20. console.log(
  21.   memoizedShape({
  22.     foo: 'foo',
  23.     bar: 123,
  24.     baz: 'baz',
  25.   }),
  26. ); // {foo: {deep: 'foo'}, bar: {deep: 'bar'}}

  27. console.log(
  28.   memoizedShape({
  29.     foo: 'not foo',
  30.     bar: 123,
  31.     baz: 'baz',
  32.   }),
  33. ); // pulled from cache
  34. ```

isPromise


boolean, _defaults to false_

Identifies the value returned from the method as a Promise, which will result in one of two possible scenarios:

- If the promise is resolved, it will fire the onCacheHit and onCacheChange options
- If the promise is rejected, it will trigger auto-removal from cache

  1. ```ts
  2. const fn = async (one: string, two: string) => {
  3.   return new Promise((resolve, reject) => {
  4.     setTimeout(() => {
  5.       reject(new Error(JSON.stringify({ one, two })));
  6.     }, 500);
  7.   });
  8. };

  9. const memoized = memoize(fn, { isPromise: true });

  10. memoized('one', 'two');

  11. console.log(memoized.cache.snapshot.keys); // [['one', 'two']]
  12. console.log(memoized.cache.snapshot.values); // [Promise]

  13. setTimeout(() => {
  14.   console.log(memoized.cache.snapshot.keys); // []
  15.   console.log(memoized.cache.snapshot.values); // []
  16. }, 1000);
  17. ```

NOTE: If you don't want rejections to auto-remove the entry from cache, set isPromise to false (or simply do not set it), but be aware this will also remove the cache listeners that fire on successful resolution.

maxSize


number, _defaults to 1_

The number of values to store in cache, based on a Least Recently Used basis. This operates the same as [maxSize](https://github.com/planttheidea/moize#maxsize) on moize.

  1. ```ts
  2. const manyPossibleArgs = (one: string, two: string) => [one, two];

  3. const memoized = memoize(manyPossibleArgs, { maxSize: 3 });

  4. console.log(memoized('one', 'two')); // ['one', 'two']
  5. console.log(memoized('two', 'three')); // ['two', 'three']
  6. console.log(memoized('three', 'four')); // ['three', 'four']

  7. console.log(memoized('one', 'two')); // pulled from cache
  8. console.log(memoized('two', 'three')); // pulled from cache
  9. console.log(memoized('three', 'four')); // pulled from cache

  10. console.log(memoized('four', 'five')); // ['four', 'five'], drops ['one', 'two'] from cache
  11. ```

onCacheAdd


function(cache: Cache, options: Options): void

Callback method that executes whenever the cache is added to. This is mainly to allow for higher-order caching managers that use micro-memoize to perform superset functionality on the cache object.

  1. ```ts
  2. const fn = (one: string, two: string) => [one, two];

  3. const memoized = memoize(fn, {
  4.   maxSize: 2,
  5.   onCacheAdd(cache, options) {
  6.     console.log('cache has been added to: ', cache);
  7.     console.log('memoized method has the following options applied: ', options);
  8.   },
  9. });

  10. memoized('foo', 'bar'); // cache has been added to
  11. memoized('foo', 'bar');
  12. memoized('foo', 'bar');

  13. memoized('bar', 'foo'); // cache has been added to
  14. memoized('bar', 'foo');
  15. memoized('bar', 'foo');

  16. memoized('foo', 'bar');
  17. memoized('foo', 'bar');
  18. memoized('foo', 'bar');
  19. ```

NOTE: This method is not executed when the cache is manually manipulated, only when changed via calling the memoized method.

onCacheChange


function(cache: Cache, options: Options): void

Callback method that executes whenever the cache is added to or the order is updated. This is mainly to allow for higher-order caching managers that use micro-memoize to perform superset functionality on the cache object.

  1. ```ts
  2. const fn = (one: string, two: string) => [one, two];

  3. const memoized = memoize(fn, {
  4.   maxSize: 2,
  5.   onCacheChange(cache, options) {
  6.     console.log('cache has changed: ', cache);
  7.     console.log('memoized method has the following options applied: ', options);
  8.   },
  9. });

  10. memoized('foo', 'bar'); // cache has changed
  11. memoized('foo', 'bar');
  12. memoized('foo', 'bar');

  13. memoized('bar', 'foo'); // cache has changed
  14. memoized('bar', 'foo');
  15. memoized('bar', 'foo');

  16. memoized('foo', 'bar'); // cache has changed
  17. memoized('foo', 'bar');
  18. memoized('foo', 'bar');
  19. ```

NOTE: This method is not executed when the cache is manually manipulated, only when changed via calling the memoized method. When the execution of other cache listeners (onCacheAdd, onCacheHit) is applicable, this method will execute after those methods.

onCacheHit


function(cache: Cache, options: Options): void

Callback method that executes whenever the cache is hit, whether the order is updated or not. This is mainly to allow for higher-order caching managers that use micro-memoize to perform superset functionality on the cache object.

  1. ```ts
  2. const fn = (one: string, two: string) => [one, two];

  3. const memoized = memoize(fn, {
  4.   maxSize: 2,
  5.   onCacheHit(cache, options) {
  6.     console.log('cache was hit: ', cache);
  7.     console.log('memoized method has the following options applied: ', options);
  8.   },
  9. });

  10. memoized('foo', 'bar');
  11. memoized('foo', 'bar'); // cache was hit
  12. memoized('foo', 'bar'); // cache was hit

  13. memoized('bar', 'foo');
  14. memoized('bar', 'foo'); // cache was hit
  15. memoized('bar', 'foo'); // cache was hit

  16. memoized('foo', 'bar'); // cache was hit
  17. memoized('foo', 'bar'); // cache was hit
  18. memoized('foo', 'bar'); // cache was hit
  19. ```

NOTE: This method is not executed when the cache is manually manipulated, only when changed via calling the memoized method.

transformKey


`function(Array): any`

A method that allows you transform the key that is used for caching, if you want to use something other than the pure arguments.

  1. ```ts
  2. const ignoreFunctionArgs = (one: string, two: () => {}) => [one, two];

  3. const memoized = memoize(ignoreFunctionArgs, {
  4.   transformKey: (args) => [JSON.stringify(args[0])],
  5. });

  6. console.log(memoized('one', () => {})); // ['one', () => {}]
  7. console.log(memoized('one', () => {})); // pulled from cache, ['one', () => {}]
  8. ```

If your transformed keys require something other than SameValueZero equality, you can combine transformKey with [isEqual](#isequal) for completely custom key creation and comparison.

  1. ```ts
  2. const ignoreFunctionArg = (one: string, two: () => void) => [one, two];

  3. const memoized = memoize(ignoreFunctionArg, {
  4.   isMatchingKey: (key1, key2) => key1[0] === key2[0],
  5.   // Cache based on the serialized first parameter
  6.   transformKey: (args) => [JSON.stringify(args[0])],
  7. });

  8. console.log(memoized('one', () => {})); // ['one', () => {}]
  9. console.log(memoized('one', () => {})); // pulled from cache, ['one', () => {}]
  10. ```

Additional properties


memoized.cache


Object

The cache object that is used internally. The shape of this structure:

  1. ```ts
  2. {
  3.   keys: any[][], // available as MicroMemoize.Key[]
  4.   values: any[] // available as MicroMemoize.Value[]
  5. }
  6. ```

The exposure of this object is to allow for manual manipulation of keys/values (injection, removal, expiration, etc).

  1. ```ts
  2. const method = (one: string, two: string) => ({ one, two });

  3. const memoized = memoize(method);

  4. memoized.cache.keys.push(['one', 'two']);
  5. memoized.cache.values.push('cached');

  6. console.log(memoized('one', 'two')); // 'cached'
  7. ```

NOTE: moize offers a variety of convenience methods for this manual cache manipulation, and while micro-memoize allows all the same capabilities by exposing the cache, it does not provide any convenience methods.

memoized.cache.snapshot


Object

This is identical to the cache object referenced above, but it is a deep clone created at request, which will provide a persistent snapshot of the values at that time. This is useful when tracking the cache changes over time, as the cache object is mutated internally for performance reasons.

memoized.fn


function

The original function passed to be memoized.

memoized.isMemoized


boolean

Hard-coded to true when the function is memoized. This is useful for introspection, to identify if a method has been memoized or not.

memoized.options


Object

The [options](#options) passed when creating the memoized method.

Benchmarks


All values provided are the number of operations per second (ops/sec) calculated by the Benchmark suite. Note thatunderscore, lodash, and ramda do not support mulitple-parameter memoization (which is where micro-memoize really shines), so they are not included in those benchmarks.

Benchmarks was performed on an i7 8-core Arch Linux laptop with 16GB of memory using NodeJS version 10.15.0. The default configuration of each library was tested with a fibonacci calculation based on the following parameters:

- Single primitive = 35
- Single object = {number: 35}
- Multiple primitives = 35, true
- Multiple objects = {number: 35}, {isComplete: true}

NOTE: Not all libraries tested support multiple parameters out of the box, but support the ability to pass a custom resolver. Because these often need to resolve to a string value, a common suggestion is to justJSON.stringify the arguments, so that is what is used when needed.

Single parameter (primitive only)


This is usually what benchmarks target for ... its the least-likely use-case, but the easiest to optimize, often at the expense of more common use-cases.

|
-----------------
fast-memoize
**micro-memoize**
lru-memoize
Addy
lodash
ramda
mem
underscore
memoizee
memoizerific

Single parameter (complex object)


This is what most memoization libraries target as the primary use-case, as it removes the complexities of multiple arguments but allows for usage with one to many values.

|
-----------------
**micro-memoize**
lodash
lru-memoize
memoizee
memoizerific
ramda
underscore
Addy
mem
fast-memoize

Multiple parameters (primitives only)


This is a very common use-case for function calls, but can be more difficult to optimize because you need to account for multiple possibilities ... did the number of arguments change, are there default arguments, etc.

|
-----------------
**micro-memoize**
lru-memoize
memoizee
Addy
memoizerific
mem
underscore
ramda
lodash
fast-memoize

Multiple parameters (complex objects)


This is the most robust use-case, with the same complexities as multiple primitives but managing bulkier objects with additional edge scenarios (destructured with defaults, for example).

|
-----------------
**micro-memoize**
lru-memoize
memoizee
memoizerific
mem
ramda
underscore
Addy
lodash
fast-memoize

Browser support


- Chrome (all versions)
- Firefox (all versions)
- Edge (all versions)
- Opera 15+
- IE 9+
- Safari 6+
- iOS 8+
- Android 4+

Node support


- 4+

Development


Standard stuff, clone the repo and npm install dependencies. The npm scripts available:

- build => run webpack to build development dist file with NODE_ENV=development
- build:minifed => run webpack to build production dist file with NODE_ENV=production
- dev => run webpack dev server to run example app (playground!)
- dist => runs build and build-minified
- lint => run ESLint against all files in the src folder
- prepublish => runs compile-for-publish
- prepublish:compile => run lint, test, transpile:es, transpile:lib, dist
- test => run AVA test functions with NODE_ENV=test
- test:coverage => run test but with nyc for coverage checker
- test:watch => run test, but with persistent watcher
- transpile:lib => run babel against all files in src to create files in lib
- transpile:es => run babel against all files in src to create files in es, preserving ES2015 modules (for [pkg.module](https://github.com/rollup/rollup/wiki/pkg.module))