- 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
廣告