- Underscore.JS 教程
- Underscore.JS - 主页
- Underscore.JS - 概述
- Underscore.JS - 环境设置
- Underscore.JS - 迭代集合
- Underscore.JS - 处理集合
- Underscore.JS - 迭代数组
- Underscore.JS - 处理数组
- Underscore.JS - 函数
- Underscore.JS - 映射对象
- Underscore.JS - 更新对象
- Underscore.JS - 比较对象
- Underscore.JS - 实用工具
- Underscore.JS - 连缀
- Underscore.JS 有用资源
- Underscore.JS - 快速指南
- Underscore.JS - 有用资源
- Underscore.JS - 讨论
Underscore.JS - memoize 方法
语法
_.memoize(function, [hashFunction])
memoize 方法加速了低速算。它通过缓存其输出来记住给定函数。如果传递了 hashFunction,则该函数用于计算哈希值,以便根据传递给原始函数的参数存储结果。请看以下示例
示例
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');
将以上程序保存在 tester.js 中。运行以下命令执行此程序。
命令
\>node tester.js
输出
4.346655768693743e+208 in 6 ms 832040 in 30 ms
underscorejs_functions.htm
广告