• Stars
    star
    2,578
  • Rank 17,780 (Top 0.4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 9 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐Ÿ‡ Fastest possible memoization library

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

More Repositories

1

bullet-train.zsh

๐Ÿš„ An oh-my-zsh shell theme based on the Powerline Vim plugin
Makefile
2,822
star
2

logdown.js

โœ๏ธ Debug utility with markdown support that runs on browser and server
JavaScript
1,023
star
3

maglev

๐Ÿš A Tmux theme made to work together with bullet-train.zsh
Shell
456
star
4

js-patterns-sublime-snippets

๐ŸŽ“ JavaScript Patterns snippets for Sublime Text
CoffeeScript
343
star
5

blooming-menu.js

๐ŸŒธ AwesomeMenu made with CSS
JavaScript
289
star
6

webpack-conditional-loader

C conditionals directive for JavaScript
JavaScript
110
star
7

tubo.js

๐Ÿ„ Your functional (sync/async) pipe | operator
JavaScript
72
star
8

superstylin

Enta in de dance, plug it in and we begin.
HTML
71
star
9

js-console-sublime-snippets

๐Ÿ’ป JavaScript and CoffeeScript Console snippets
CoffeeScript
61
star
10

video-stream.js

๐Ÿ”œ ๐Ÿ“ผ Video stream middleware for express.js
JavaScript
43
star
11

js-konami-code-event

Konami code event for your HTML5 web app/page
JavaScript
40
star
12

alfred-chrome-window-workflow

Alfred.app workflow for creating new Chrome windows
AppleScript
37
star
13

jasmine-sublime-snippets

Snippets for Jasmine, the BDD framework for testing JavaScript, in Sublime Text
Python
35
star
14

monocle-decorators.js

๐ŸŽฉ Classy decorators
JavaScript
32
star
15

chrome-blank-new-tab

Dark blank new tab extension for Chrome.
HTML
31
star
16

keynote-grid

A grid template for Keynote.app
30
star
17

piao-da-casa-propria-em-css-3d

Piรฃo da Casa Prรณpria 100% em HTML5
HTML
28
star
18

laughing-man.js

JavaScript
22
star
19

safe-chain.js

๐Ÿ”— No more crazy checks to safely get a nested value inside an object
JavaScript
21
star
20

redux-whenever.js

๐Ÿ•Ÿ Redux store subscriber for specific state change
JavaScript
21
star
21

parse-price.js

๐Ÿ’ต Returns a Number from a localized price string.
JavaScript
21
star
22

alfred-iterm-workflow

Alfred.app workflow for iTerm2
AppleScript
19
star
23

javascript-environments-logos

PostScript
15
star
24

html-style-guide

13
star
25

hide-virtual-keyboard.js

๐Ÿ“ฑ Hides virtual keyboard on a real mobile device (iPhone, Android, ...)
JavaScript
12
star
26

ken-burns-slideshow

๐ŸŽ‡ A slideshow in JS with the Ken Burns effect.
JavaScript
12
star
27

knowledge

๐Ÿ“– Tips and tricks I learned along the way
12
star
28

js-debounce-throttle-visual-explanation

A visual explanation about the *Throttle* and *Debounce* design patterns
JavaScript
11
star
29

alfred-credit-card-numbers

Credit card fake numbers workflow for Alfred.app
Python
8
star
30

redux-logdown.js

Redux logging middleware
JavaScript
8
star
31

alfred-feline-theme

An OS X-like theme for Alfred
8
star
32

stubbable-decorator.js

๐ŸŒฒ Decorator to stub modules in ECMAScript 2015+
JavaScript
8
star
33

obstructed.js

๐Ÿš Checks if the main thread is busy, executing a callback whenever it happens
JavaScript
7
star
34

with-subscribe.js

Minimal Observable interface to watch for object modifications.
JavaScript
7
star
35

logdown-cast.js

๐Ÿ“ก Subscribe to a remote logdown instance
JavaScript
6
star
36

city-state.js

๐Ÿ‘‘ Observable and encapsulated state management
JavaScript
6
star
37

times-square

Color scheme
JavaScript
6
star
38

caiogondim.com

๐Ÿ“ where i write about random things, at random times
JavaScript
6
star
39

timeout-racer.js

๐ŸŽ๏ธ Timeout for promises race
JavaScript
5
star
40

simopen

๐Ÿ“ฑ Opens given URL on iOS simulator.
JavaScript
5
star
41

quickreturn.js

:squirrel: QuickReturn Android pattern to the web
JavaScript
5
star
42

jquery-first-event

๐Ÿ† Execute your event listener callback before others
JavaScript
5
star
43

hourglass.js

โง—
JavaScript
4
star
44

js-underscore.tmbundle

A TextMate bundle for the JavaScript Underscore library
4
star
45

css3-lightbulb-with-ambient-light-sensor

a light bulb in CSS3 with ambient light awareness
CSS
4
star
46

react-with-dimensions

โš›๏ธ React decorator to receive dimensions props generated by ResizeObserver.
JavaScript
4
star
47

solar-system

A solar system entirely built with <canvas> and no external libs
JavaScript
4
star
48

arg-type.js

Like prop-types, but for vanilla JavaScript
JavaScript
4
star
49

programming-challenges

Rust
3
star
50

alfred-sublime-text-window-workflow

A workflow to create Sublime Text windows without having to be in it's context.
AppleScript
3
star
51

resilient.js

Resilient JS loader
JavaScript
3
star
52

docker-node-puppeteer

Dockerfile
3
star
53

gridlock.css

๐Ÿš™ ๐Ÿš— Small CSS grid layout implemented with flexbox
HTML
3
star
54

corleone.js

DOM utilities
JavaScript
3
star
55

idle-promise.js

requestIdleCallback with a Promise interface and setTimeout fallback
JavaScript
2
star
56

murmurhash-wasm

2
star
57

js-style-guide

A remix of everybody's JavaScript style guide
JavaScript
2
star
58

sieve-of-eratosthenes-rust

Rust
2
star
59

signalhub-server.js

2
star
60

observable.js

Minimal Observable interface
2
star
61

alfred-firefox-window-workflow

new Firefox window workflow for Alfred.app
AppleScript
2
star
62

webpix

Um experimento HTML5 com cรขmera, canvas e download sem back-end
JavaScript
2
star
63

css-transform-interactive

Learn CSS transform in a more interactive and fun way
CSS
2
star
64

dotfiles

โšช My dotfiles
Lua
2
star
65

gulp-filename-hint

Gulp plugin for linting filenames
JavaScript
2
star
66

strict-dict.js

Object (dictionary) that throws TypeError when trying to get an undefined property.
JavaScript
2
star
67

node-calculadora

Exemplo de projeto Git para o Front-end United
JavaScript
1
star
68

msleep

โ›” Small function that mimics the usleep C function, blocking the main thread
JavaScript
1
star
69

white-lion

A Growl Theme based on OS X Lion
1
star
70

css-style-guide

1
star
71

get-highest-z-index.js

JavaScript
1
star
72

tip-calculator

HTML
1
star
73

async-preload-img

Promise based image preloader
JavaScript
1
star
74

react-prefetchable

JavaScript
1
star
75

hal

JavaScript
1
star
76

mouse-polling-rate

HTML
1
star
77

sale.caiogondim.com

I'm moving to New York and selling all my stuff for a reasonable price.
HTML
1
star
78

strip-margin.js

JavaScript
1
star
79

eslint-direct-children-dependency

1
star
80

set-state-redux.js

Love and setState is all you need
JavaScript
1
star
81

invoke-without-new.js

Invoke constructors without new
JavaScript
1
star
82

type-from.js

Get type from given argument
JavaScript
1
star
83

advent-of-code-2022

1
star
84

streams

repository hosting test streams used by hls.js
1
star
85

alfred-itunes-playback-workflow

An Aflred.app workflow to control repeat and shuffle in iTunes
AppleScript
1
star
86

mocker

JavaScript
1
star