Underscore.JS - memoize method



Syntax

_.memoize(function, [hashFunction])

memoize method speeds up the slow computation. It remembers the a given function by caching its output. hashFunction if passed is used to compute the hash value to store the result based on arguments passed to original function. See the below example

Example

var _ = require('underscore');

var fibonacci = _.memoize(function(n) {
  return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);
});

var fibonacci1 = function(n) {
  return n < 2 ? n: fibonacci1(n - 1) + fibonacci1(n - 2);
};

var startTimestamp = new Date().getTime();
var result = fibonacci(1000);
var endTimestamp = new Date().getTime();
console.log(result + " in " + ((endTimestamp - startTimestamp)) + ' ms');

startTimestamp = new Date().getTime();
result = fibonacci1(30);
endTimestamp = new Date().getTime();
console.log(result + " in " + ((endTimestamp - startTimestamp)) + ' ms');

Save the above program in tester.js. Run the following command to execute this program.

Command

\>node tester.js

Output

4.346655768693743e+208 in 6 ms
832040 in 30 ms
underscorejs_functions.htm
Advertisements