4.1.2 • Published 3 months ago

micro-memoize v4.1.2

Weekly downloads
163,928
License
MIT
Repository
github
Last release
3 months ago

micro-memoize

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

Table of contents

Summary

As the author of 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.2kB minified+gzipped). Stripping out these edge cases also allows micro-memoize to be faster across the board than moize.

Importing

ESM in browsers:

import memoize from 'micro-memoize';

ESM in NodeJS:

import memoize from 'micro-memoize/mjs';

CommonJS:

const memoize = require('micro-memoize').default;

Usage

// ES2015+
import memoize from 'micro-memoize';

// CommonJS
const memoize = require('micro-memoize').default;

// old-school
const memoize = window.memoize;

const assembleToObject = (one, two) => {
  return { one, two };
};

const memoized = memoize(assembleToObject);

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

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
import { deepEqual } from 'fast-equals';

const deepObject = object => {
  return {
    foo: object.foo,
    bar: object.bar,
  };
};

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

console.log(
  memoizedDeepObject({
    foo: {
      deep: 'foo',
    },
    bar: {
      deep: 'bar',
    },
    baz: {
      deep: 'baz',
    },
  }),
); // {foo: {deep: 'foo'}, bar: {deep: 'bar'}}

console.log(
  memoizedDeepObject({
    foo: {
      deep: 'foo',
    },
    bar: {
      deep: 'bar',
    },
    baz: {
      deep: 'baz',
    },
  }),
); // pulled from cache

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

isMatchingKey

function(object1: Array<any>, object2: Array<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
import { deepEqual } from 'fast-equals';

const deepObject = object => {
  return {
    foo: object.foo,
    bar: object.bar,
  };
};

const memoizedShape = memoize(deepObject, {
  isMatchingKey(object1, object2) {
    return (
      object1.hasOwnProperty('foo') &&
      object2.hasOwnProperty('foo') &&
      object1.bar === object2.bar
    );
  },
});

console.log(
  memoizedShape({
    foo: 'foo',
    bar: 'bar',
    baz: 'baz',
  }),
); // {foo: {deep: 'foo'}, bar: {deep: 'bar'}}

console.log(
  memoizedShape({
    foo: 'not foo',
    bar: 'bar',
    baz: 'baz',
  }),
); // pulled from cache

isPromise

boolean, defaults to boolean

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
const fn = async (one, two) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject(new Error({ one, two }));
    }, 500);
  });
};

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

memoized('one', 'two');

console.log(memoized.cacheSnapshot.keys); // [['one', 'two']]
console.log(memoized.cacheSnapshot.values); // [Promise]

setTimeout(() => {
  console.log(memoized.cacheSnapshot.keys); // []
  console.log(memoized.cacheSnapshot.values); // []
}, 1000);

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 on moize, with the exception of the default being different.

const manyPossibleArgs = (one, two) => {
  return [one, two];
};

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

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

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

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

NOTE: The default for micro-memoize differs from the default implementation of moize. moize will store an infinite number of results unless restricted, whereas micro-memoize will only store the most recent result. In this way, the default implementation of micro-memoize operates more like moize.simple.

onCacheAdd

function(cache: Cache, options: Options): void, defaults to noop

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.

const fn = (one, two) => {
  return [one, two];
};

const memoized = memoize(fn, {
  onCacheAdd(cache, options) {
    console.log('cache has been added to: ', cache);
    console.log('memoized method has the following options applied: ', options);
  },
});

memoized('foo', 'bar'); // cache has been added to
memoized('foo', 'bar');
memoized('foo', 'bar');

memoized('bar', 'foo'); // cache has been added to
memoized('bar', 'foo');
memoized('bar', 'foo');

memoized('foo', 'bar');
memoized('foo', 'bar');
memoized('foo', 'bar');

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, defaults to noop

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.

const fn = (one, two) => {
  return [one, two];
};

const memoized = memoize(fn, {
  onCacheChange(cache, options) {
    console.log('cache has changed: ', cache);
    console.log('memoized method has the following options applied: ', options);
  },
});

memoized('foo', 'bar'); // cache has changed
memoized('foo', 'bar');
memoized('foo', 'bar');

memoized('bar', 'foo'); // cache has changed
memoized('bar', 'foo');
memoized('bar', 'foo');

memoized('foo', 'bar'); // cache has changed
memoized('foo', 'bar');
memoized('foo', 'bar');

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, defaults to noop

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.

const fn = (one, two) => {
  return [one, two];
};

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

memoized('foo', 'bar');
memoized('foo', 'bar'); // cache was hit
memoized('foo', 'bar'); // cache was hit

memoized('bar', 'foo');
memoized('bar', 'foo'); // cache was hit
memoized('bar', 'foo'); // cache was hit

memoized('foo', 'bar'); // cache was hit
memoized('foo', 'bar'); // cache was hit
memoized('foo', 'bar'); // cache was hit

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

transformKey

function(Array<any>): 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.

const ignoreFunctionArgs = (one, two) => {
  return [one, two];
};

const memoized = memoize(ignoreFunctionArgs, {
  transformKey: JSON.stringify,
});

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

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

const ignoreFunctionArgs = (one, two) => {
  return [one, two];
};

const memoized = memoize(ignoreFunctionArgs, {
  isEqual(key1, key2) {
    return key1.args === key2.args;
  },
  transformKey(args) {
    return {
      args: JSON.stringify(args),
    };
  },
});

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

Additional properties

cache

Object

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

{
  keys: Array<Array<any>>, // array of arg arrays
  values: Array<any> // array of values
}

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

const method = (one, two) => {
  return { one, two };
};

const memoized = memoize(method);

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

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

HOTE: 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.

cacheSnapshot

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.

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.

options

Object

The 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 that underscore, 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 8.9.4. 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}

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.

Operations / secondRelative margin of error
fast-memoize219,525,9430.56%
micro-memoize76,004,2341.12%
lodash26,920,9880.65%
underscore24,126,3350.73%
memoizee16,575,2370.74%
lru-memoize8,016,2371.58%
Addy Osmani6,476,5330.96%
memoizerific5,511,2330.78%
ramda1,107,3190.68%

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.

Operations / secondRelative margin of error
micro-memoize60,533,0960.68%
memoizee11,601,1860.82%
lodash8,017,6340.77%
underscore7,910,1750.76%
lru-memoize6,878,2491.12%
memoizerific4.377,0620.74%
Addy Osmani1,829,2560.74%
fast-memoize1,468,2720.67%
ramda213,1180.84%

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.

Operations / secondRelative margin of error
micro-memoize49,690,8211.26%
memoizee10,425,2650.76%
lru-memoize6,165,9180.76%
memoizerific4,587,0500.72%
Addy Osmani3,409,9410.67%
fast-memoize1,214,6160.66%

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

Operations / secondRelative margin of error
micro-memoize47,300,3391.20%
memoizee7,487,5820.73%
lru-memoize6,287,8931.15%
memoizerific3,537,6900.75%
Addy Osmani936,2730.70%
fast-memoize808,1410.68%

Browser support

  • Chrome (all versions)
  • executefox (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)
@kaltura-ott/rhino@caredoc/next-utils@caredoc/react-hooks-web@infinitebrahmanuniverse/nolb-micro-esm-payload@everything-registry/sub-chunk-2165@itoa/itoa@itoa/keystoneultra-runnerv-ii-fe-coreunified-vscodedabsi-payload@layerzerolabs/devtools-evm-hardhat@mpal9000/ts-core@obigtech/ui-core@ocopjs/ocopreact-native-dynamic-style-processorreact-native-css-media-query-processor@sngular/open-api-mocker@shipt/react-native-tachyons@nfq/open-api-mocker@nikolarhristov/payloadopen-api-mocker@janus-idp/backstage-plugin-kiali@koikorn/keystone@koikorn/logger@keystonejs/keystone@keystonejs/loggerprettier-plugin-embed@trendmicro/react-styled-ui@re-/assert@stacks/ui-corepearlpayloadddjohnpayload-john@itwin/presentation-componentswyginincposthtml-relative-paths@tonic-ui/react-lab@tonic-ui/react@wisefy/payload@blueprint-blocks/components@blueprint-blocks/utility@debridge-finance/solana-contracts-client@debridge-finance/solana-utils@coductsolutions/open-api-mocker@democrance/utilsrefinejs-repo@xcritical/select@xcritical/switch@xcritical/theme@xcritical/inline-edit@xcritical/input@xcritical/modal@xcritical/badge@xcritical/button@xcritical/checkbox@xcritical/drawerremeasure@syvita/ui-corerehype-lqipibiza@vitro/cli@vitro/codemodremark-vscode@compiled-system/core@dpendrak/payload@davidscicluna/component-library@gravitylabs/react-native-css-media-query-processor@caredoc/utils-webkiali-ui@bundless/cli@bundless/plugin-react-paged@bentley/presentation-componentsjotai-stories@fungible-systems/rich-markdown-editor@funya._./react-native-dynamic-style-processorjess@eslint-react/jsx@holocron.so/componentsmoizemoize-importmoize-import-type@extractus/extractus@extractus/utilscodemod-split-classnamestiled-canvas
5.0.0-beta.2

3 months ago

5.0.0-beta.1

4 months ago

5.0.0-beta.0

4 months ago

4.1.1-beta.0

12 months ago

4.1.1-beta.1

12 months ago

4.0.15

12 months ago

4.1.0-beta.0

12 months ago

4.1.0-beta.1

12 months ago

4.1.0-beta.4

12 months ago

4.1.0-beta.2

12 months ago

4.1.0-beta.3

12 months ago

4.1.0

12 months ago

4.1.2

12 months ago

4.1.1

12 months ago

4.0.12

1 year ago

4.0.14

1 year ago

4.0.13

1 year ago

4.0.11

2 years ago

4.0.10

2 years ago

4.0.9

4 years ago

4.0.8

5 years ago

4.0.8-beta.0

5 years ago

4.0.7

5 years ago

4.0.6

5 years ago

4.0.5

5 years ago

4.0.4

5 years ago

4.0.3

5 years ago

4.0.2

5 years ago

4.0.2-beta.1

5 years ago

4.0.2-beta.0

5 years ago

4.0.1

5 years ago

4.0.0

5 years ago

3.0.2

5 years ago

3.1.0-beta.1

5 years ago

3.1.0-beta.0

5 years ago

3.0.1

5 years ago

3.0.0

5 years ago

3.0.0-beta.6

5 years ago

3.0.0-beta.5

5 years ago

3.0.0-beta.4

5 years ago

3.0.0-beta.3

5 years ago

3.0.0-beta.2

5 years ago

3.0.0-beta.1

5 years ago

3.0.0-beta.0

5 years ago

2.1.2

6 years ago

2.1.1

6 years ago

2.1.0

6 years ago

2.0.4

6 years ago

2.0.3

6 years ago

2.0.2

6 years ago

2.0.1

6 years ago

2.0.0

6 years ago

1.8.1

6 years ago

1.8.0

6 years ago

1.7.0

6 years ago

1.6.3

6 years ago

1.6.2

6 years ago

1.6.1

6 years ago

1.6.0

6 years ago

1.5.0

6 years ago

1.4.0

6 years ago

1.3.2

6 years ago

1.3.1

6 years ago

1.3.0

6 years ago

1.2.0

6 years ago

1.1.0

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago