All Projects → caiogondim → Fast Memoize.js

caiogondim / Fast Memoize.js

Licence: mit
🐇 Fastest possible memoization library

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects
shell
77523 projects

Projects that are alternatives of or similar to Fast Memoize.js

Cached
Rust cache structures and easy function memoization
Stars: ✭ 530 (-78.61%)
Mutual labels:  memoization
Memery
A gem for memoization in Ruby
Stars: ✭ 98 (-96.05%)
Mutual labels:  memoization
Pegparser
💡 Build your own programming language! A C++17 PEG parser generator supporting parser combination, memoization, left-recursion and context-dependent grammars.
Stars: ✭ 164 (-93.38%)
Mutual labels:  memoization
Re Reselect
Enhance Reselect selectors with deeper memoization and cache management.
Stars: ✭ 932 (-62.39%)
Mutual labels:  memoization
React Selector Hooks
Collection of hook-based memoized selector factories for declarations outside of render.
Stars: ✭ 84 (-96.61%)
Mutual labels:  memoization
Frontend Computer Science
A list of Computer Science topics important for a Front-End Developer to learn 📝
Stars: ✭ 113 (-95.44%)
Mutual labels:  memoization
Memoize State
The magic memoization for the State management. ✨🧠
Stars: ✭ 305 (-87.69%)
Mutual labels:  memoization
Joblib
Computing with Python functions.
Stars: ✭ 2,620 (+5.73%)
Mutual labels:  memoization
Beautiful React Redux
Redux 🚀, Redux 🤘, Redux 🔥 - and the magic optimization
Stars: ✭ 87 (-96.49%)
Mutual labels:  memoization
Use Inline Memo
⚛️ React hook for memoizing values inline anywhere in a component
Stars: ✭ 152 (-93.87%)
Mutual labels:  memoization
Immutable Tuple
Immutable finite list objects with constant-time equality testing (===) and no memory leaks.
Stars: ✭ 29 (-98.83%)
Mutual labels:  memoization
Decko
💨 The 3 most useful ES7 decorators: bind, debounce and memoize
Stars: ✭ 1,024 (-58.68%)
Mutual labels:  memoization
Micro Memoize
A tiny, crazy fast memoization library for the 95% use-case
Stars: ✭ 135 (-94.55%)
Mutual labels:  memoization
Moize
The consistently-fast, complete memoization solution for JS
Stars: ✭ 628 (-74.66%)
Mutual labels:  memoization
Leetcode
High-quality LeetCode solutions
Stars: ✭ 178 (-92.82%)
Mutual labels:  memoization
Cachier
Persistent, stale-free, local and cross-machine caching for Python functions.
Stars: ✭ 359 (-85.51%)
Mutual labels:  memoization
Python Memoization
A powerful caching library for Python, with TTL support and multiple algorithm options.
Stars: ✭ 109 (-95.6%)
Mutual labels:  memoization
Memoize One
A memoization library which only remembers the latest invocation
Stars: ✭ 2,649 (+6.9%)
Mutual labels:  memoization
Memo Decorator
Decorator which applies memoization to a method of a class.
Stars: ✭ 213 (-91.4%)
Mutual labels:  memoization
Data Structures
Common data structures and algorithms implemented in JavaScript
Stars: ✭ 139 (-94.39%)
Mutual labels:  memoization

fast-memoize

 Travis CI Code coverage

In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again. — Wikipedia

This library is an attempt to make the fastest possible memoization library in JavaScript that supports N arguments.

Installation

npm install fast-memoize --save

Usage

const memoize = require('fast-memoize')

const fn = function (one, two, three) { /* ... */ }

const memoized = memoize(fn)

memoized('foo', 3, 'bar')
memoized('foo', 3, 'bar') // Cache hit

Custom cache

The fastest cache is used for the running environment, but it is possible to pass a custom cache to be used.

const memoized = memoize(fn, {
  cache: {
    create() {
      var store = {};
      return {
        has(key) { return (key in store); },
        get(key) { return store[key]; },
        set(key, value) { store[key] = value; }
      };
    }
  }
})

The custom cache should be an object containing a create method that returns an object implementing the following methods:

  • get
  • set
  • has

Custom serializer

To use a custom serializer:

const memoized = memoize(fn, {
  serializer: customSerializer
})

The serializer is a function that receives one argument and outputs a string that represents it. It has to be a deterministic algorithm meaning that, given one input, it always returns the same output.

Benchmark

For an in depth explanation on how this library was created, go read this post on RisingStack.

Below you can see a performance benchmark between some of the most popular libraries for memoization.

To run the benchmark, clone the repo, install the dependencies and run npm run benchmark.

git clone [email protected]:caiogondim/fast-memoize.git
cd fast-memoize
npm install
npm run benchmark

Against another git hash

To benchmark the current code against a git hash, branch, ...

npm run benchmark:compare 53fa9a62214e816cf8b5b4fa291c38f1d63677b9

Gotchas

Rest & Default Parameters

We check for function.length to get upfront the expected number of arguments in order to use the fastest strategy. But when rest & default parameters are being used, we don't receive the right number of arguments (see details).

// Rest parameter example
function multiply (multiplier, ...theArgs) {
  return theArgs.map(function (element) {
    return multiplier * element
  })
}
multiply.length // => 1

// Default parameter example
function divide (element, divisor = 1) {
  return divisor * element
}
divide.length // => 1

So if you use rest & default parameters, explicitly set the strategy to variadic.

const memoizedMultiply = memoize(multiply, {
  strategy: memoize.strategies.variadic
})

Function Arguments

The default serializer uses JSON.stringify which will serialize functions as null. This means that if you are passing any functions as arguments you will get the same output regardless of whether you pass in different functions or indeed no function at all. The cache key generated will always be the same. To get around this you can give each function a unique ID and use that.

let id = 0
function memoizedId(x) {
  if (!x.__memoizedId) x.__memoizedId = ++id
  return { __memoizedId: x.__memoizedId }
}

memoize((aFunction, foo) => {
  return aFunction.bind(foo)
}, {
  serializer: args => {
    const argumentsWithFuncIds = Array.from(args).map(x => {
      if (typeof x === 'function') return memoizedId(x)
      return x
    })
    return JSON.stringify(argumentsWithFuncIds)
  }
})

Credits


caiogondim.com  ·  GitHub @caiogondim  ·  Twitter @caio_gondim

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].