tim*_*son 3 javascript php recursion memoization
我找到了例如因子计算的例子来解释记忆.这些都很有帮助,但我正在寻求更深入的了解.
我想知道是否有人可以描述这种技术的真实世界应用以及为什么他们使用它而不是递归或者他们使用memoization感觉到的任何其他可能有助于他们优化.
记忆比缓存更具体.
考虑使用选择器在DOM中搜索元素,就像使用jQuery一样.说,$('.some-selector').在这个上下文中,我正在调用该函数$,告诉它为我找到所有具有CSS选择器'.some-selector'的元素.假设文档很大,我需要$('.some-selector')多次调用.
您可以假设每次调用$('.some-selector')都将返回相同的结果,因此,每次调用它时进行实际处理都是浪费精力.因此,$可以使用参数(在这种情况下为".some-selector")作为某些查找表或字典中的键.第一次使用该参数调用函数时,它会正常处理,结果将使用参数作为键放在字典中,并返回结果.后续调用将发现该键在字典中具有表示已经计算的结果的值,因此它只返回那些先前的结果.最终效果是您不会浪费时间查找您已经知道的结果.
一个粗略的JavaScript示例:
var _dictionary = {};
function $(selector) {
if (_dictionary[selector]) return _dictionary[selector]; // lookup the results of the selector and return them if they exist
// otherwise, execute the function's logic normally
// TODO: search logic
var results = doSearch();
_dictionary[selector] = results;
return results;
}
Run Code Online (Sandbox Code Playgroud)
此链接更详细,甚至包括memoize可用于任何其他功能的通用JS功能.