Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
memoizerific
Advanced tools
memoizerific is a JavaScript library that provides a simple and efficient way to memoize functions. Memoization is a technique used to speed up function execution by caching the results of expensive function calls and returning the cached result when the same inputs occur again.
Basic Memoization
This feature allows you to memoize a function with a specified cache size. In this example, the function adds two numbers and caches the result for up to 100 different input combinations.
const memoizerific = require('memoizerific');
const memoizedFunction = memoizerific(100)((a, b) => a + b);
console.log(memoizedFunction(1, 2)); // 3
console.log(memoizedFunction(1, 2)); // 3 (cached result)
Cache Size Limitation
This feature demonstrates how the cache size limitation works. When the cache exceeds the specified size, the oldest cached result is evicted.
const memoizerific = require('memoizerific');
const memoizedFunction = memoizerific(2)((a, b) => a + b);
memoizedFunction(1, 2); // Cache: {(1, 2): 3}
memoizedFunction(2, 3); // Cache: {(1, 2): 3, (2, 3): 5}
memoizedFunction(3, 4); // Cache: {(2, 3): 5, (3, 4): 7} (1, 2) is evicted
Function Argument Handling
This feature shows how memoizerific can handle functions with variable numbers of arguments. The function sums all its arguments and caches the result.
const memoizerific = require('memoizerific');
const memoizedFunction = memoizerific(100)((...args) => args.reduce((sum, val) => sum + val, 0));
console.log(memoizedFunction(1, 2, 3)); // 6
console.log(memoizedFunction(1, 2, 3)); // 6 (cached result)
lodash.memoize is a function from the Lodash library that provides similar memoization capabilities. It allows you to memoize functions and customize the cache key resolver. Compared to memoizerific, lodash.memoize is part of a larger utility library and may offer more flexibility in terms of cache key customization.
fast-memoize is a lightweight and fast memoization library. It focuses on performance and simplicity, making it a good alternative to memoizerific for scenarios where speed is critical. However, it may not offer as many features as memoizerific, such as cache size limitation.
memoizee is a comprehensive memoization library that offers a wide range of features, including cache size limitation, cache expiration, and support for various cache storage mechanisms. It is more feature-rich compared to memoizerific but may be more complex to use.
Fastest (see benchmarks), smallest (923b min/gzip), most-efficient, dependency-free, JavaScript (JS) memoization lib. Fully supports multiple complex object arguments. Implements LRU (least recently used) cache to maintain only the most recent results.
For the browser and nodejs.
Memoization is the process of caching function results so that they can be returned cheaply without re-running the function when it is re-invoked with the same arguments.
npm install memoizerific --save
var memoizerific = require('memoizerific');
var myExpensiveFunctionMemoized = memoizerific(50)(function(arg1, arg2, arg3) {
// so many long expensive calls in here
});
myExpensiveFunction(1, 2, 3); // damn, that took looooong to process
myExpensiveFunction(1, 2, 3); // wow, that one was instant!
myExpensiveFunction(2, 3, 4); // expensive again :(
myExpensiveFunction(2, 3, 4); // woah, this one was dirt cheap, I'll take 2!
There is one option available:
limit:
the max number of results to cache.
memoizerific(limit)(fn);
memoizerific(1)(function(){}); // memoize 1 result
memoizerific(10000)(function(){}); // memoize 10,000 results
memoizerific(0)(function(){}); // memoize infinity results (not recommended)
The cache works using LRU logic (least recently used), purging the oldest results when the limit is reached.
// memoize 1 result
var myMemoized = memoizerific(1)(function(arg1, arg2, arg3, arg4) {});
myMemoized(1, 2, 3, 'a'); // function runs
myMemoized(1, 2, 3, 'a'); // cached result is returned
myMemoized(1, 2, 3, 'X'); // function runs again, new result is cached, old cached result is purged
myMemoized(1, 2, 3, 'X'); // new cached result is returned
myMemoized(1, 2, 3, 'a'); // function runs again...
There are many memoization libs available for JavaScript. Some of them have specialized use-cases, such as memoizing file-system access, or server async requests. While others, such as this library, tackle the more general use-case of memoizing standard synchronous functions. Few, however, are suitable for real-world production environments. Following are the minimum criteria I look for in a professional memoization solution:
Using this simply list, we can narrow down the field of possible candidates dramatically. The popular lodash solution, for example, only supports one argument out of the box and has no cache-size control. Others support multiple complex arguments, but do not provide cache-size control solution:
:heavy_multiplication_x: Memoizejs (@addyosmani)
:heavy_multiplication_x: Memoize-strict (@jshanson7)
:heavy_multiplication_x: Deep-memoize (@rjmk)
:heavy_multiplication_x: Mem (@sindresorhus)
Three libs with reasonable traction, seem to meet the basic criteria:
After some quick testing, however, the library by @neilk was simply producing incorrect results, leaving two viable candidates. Time to test performance.
This library is intended for real-world use-cases, and is therefore benchmarked against other libraries using large, complex, real-world data. Humanity doesn't need any more fibonacci solvers after all. Example arguments look like this:
myMemoized(
{ a: 1, b: [{ c: 2, d: { e: 3 }}] }, // 1st argument
[{ x: 'x', q: 'q', }, { b: 8, c: 9 }, { b: 2, c: [{x: 5, y: 3}, {x: 2, y: 7}] }, { b: 8, c: 9 }, { b: 8, c: 9 }], // 2nd argument
{ z: 'z' }, // 3rd argument
... // 4th, 5th... argument
);
We generated sets of thousands of random argument combinations of varying variance (to increase and decrease cache hits and misses) and fed them each the same ones. For the full details and source of the benchmarks see memoize-js-libs-benchmarks.
Following is data from 5000 iterations for each test on firefox 44:
Cache Size | Num Args | Approx. Cache Hits (variance) | LRU-Memoize | Memoizee | Memoizerific | % Faster |
---|---|---|---|---|---|---|
10 | 2 | 99% | 19ms | 31ms | 10ms | 90% |
10 | 2 | 62% | 212ms | 319ms | 172ms | 23% |
10 | 2 | 7% | 579ms | 617ms | 518ms | 12% |
100 | 2 | 99% | 137ms | 37ms | 20ms | 85% |
100 | 2 | 69% | 696ms | 245ms | 161ms | 52% |
100 | 2 | 10% | 1,057ms | 649ms | 527ms | 23% |
500 | 4 | 95% | 476ms | 67ms | 62ms | 8% |
500 | 4 | 36% | 2,642ms | 703ms | 594ms | 18% |
500 | 4 | 11% | 3,619ms | 880ms | 725ms | 21% |
1000 | 8 | 95% | 1,009ms | 52ms | 65ms | 25% |
1000 | 8 | 14% | 10,477ms | 659ms | 635ms | 4% |
1000 | 8 | 1% | 6,943ms | 1,501ms | 1,466ms | 2% |
The results from these tests are interesting. While LRU-Memoize performed quite well when there were few arguments, and lots of cache hits, it quickly started to fall apart as the environment became more challenging. Once we got to 4 arguments it became 5x-10x-20x slower than the other two, and began to hit severe levels that could potentially cause real-life problems. I would not recommend it for heavy production use. Memoizee came in a solid second place, being outperformed by Memoizerific by an average of 31%. While not insignificant, in many real-world scenarios this will not make a huge difference, unless the memoized function is being called repetitively in a loop, or through heavy recursion. What counts, is that it degraded nicely, and stayed within reasonable sub 1s levels. It is a sturdy library and I would be comfortable recommending it for production use. Memoizerific was clearly the big performance winner. It was built with complex real-world use in mind, and I would biasedly recommend it.
FAQs
Fast, small, efficient JavaScript memoization lib to memoize JS functions
The npm package memoizerific receives a total of 5,432,698 weekly downloads. As such, memoizerific popularity was classified as popular.
We found that memoizerific demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.