使用场景
- 当一些计算结果可以保留下来为以后的运算提供方便的时候, 就可以用到记忆话函数
- 记忆化函数将计算结果存储起来,如果之后碰到相同的参数,就直接放回已经计算过的参数
代码
- 记忆函数
function memorize(func) {
var cache = {};
return function() {
//让参数长度与参数拼接成字符串,例如1,2 -> 212,形成唯一的key值
var key = arguments.length + Array.prototype.join.call(arguments);
if (cache[key]) {
return cache[key];
} else {
console.log(arguments)
cache[key] = func.apply(this, arguments);
return cache[key];
}
};
}
- 去重
function deepCopy(o) {
let newObj = o instanceof Array ? [] : {};
for (var prop in o) {
if (typeof o[prop] == "object") {
newObj[prop] = deepCopy(o[prop]);
} else {
newObj[prop] = o[prop];
}
}
return newObj;
}
- 对比运行时间
var list = [
{
id: "1",
menu_name: "设置",
menu_url: "setting",
parent_id: 0
},
{
id: "1-1",
menu_name: "权限设置",
menu_url: "setting.permission",
parent_id: "1"
},
{
id: "1-1-1",
menu_name: "用户管理列表",
menu_url: "setting.permission.user_list",
parent_id: "1-1"
},
{
id: "1-1-2",
menu_name: "用户管理新增",
menu_url: "setting.permission.user_add",
parent_id: "1-1"
},
{
id: "1-2",
menu_name: "菜单设置",
menu_url: "setting.menu",
parent_id: "1"
},
{
id: "1-2-1",
menu_name: "菜单列表",
menu_url: "setting.menu.menu_list",
parent_id: "1-2"
}
];
var memorizeFunc = memorize(deepCopy);
// console.log()
console.time("pre");
console.log(deepCopy(list));
console.timeEnd("pre"); // 3.162841796875ms
console.time("mem");
console.log(memorizeFunc(list));
console.timeEnd("mem");
-
节省了2ms
image.png
网友评论