问题描述
我找到了诸如阶乘计算之类的例子来解释。这些都很有用,但我正在寻求更深入的理解。
I've found examples such as factorial calculation to explain memoization. These are helpful but I'm looking for a deeper understanding.
我想知道是否有人可以描述这种技术的真实世界应用以及为什么他们使用它代替递归或他们使用memoization感觉到的任何其他东西可能有助于他们优化。
I'm wondering if someone can describe a real world application of this technique and why they used it instead of recursion or whatever else they felt using memoization might help them optimize.
推荐答案
记忆比缓存更具体。
考虑使用选择器在DOM中搜索元素,就像使用jQuery一样。比如说, $('。some-selector')
。在这个上下文中,我正在调用函数 $
,告诉它为我找到所有具有CSS选择器'.some-selector'的元素。假设文档很大,我需要多次调用 $('。some-selector')
。
Think about searching for an element in the DOM using a selector, like you might with jQuery. Say, $('.some-selector')
. In this context, I'm calling the function $
, telling it to find for me all elements that have the CSS selector '.some-selector'. Let's say that the document is large, and I need to call $('.some-selector')
many times.
您可以假设每次调用 $('。some-selector')
都将返回相同的结果,因此,每次执行实际处理被调用的时间是浪费精力。因此, $
可以使用参数(在本例中为.some-selector)作为某些查找表或字典中的键。第一次使用该参数调用函数时,它会正常处理,结果将使用参数作为键放在字典中,并返回结果。后续调用将发现该键在字典中具有表示已经计算的结果的值,因此它只返回那些先前的结果。最终效果是你不会浪费时间找到你已经知道的结果。
You can make the assumption that every call to $('.some-selector')
is going to return the same results, and therefore, doing the actual processing each time it is invoked is wasted effort. Therefore, $
could use the argument ('.some-selector', in this case) as a key in some lookup table or dictionary. The first time the function is invoked with that argument, it is processed normally, the results are placed in the dictionary using the argument as a key, and the results are returned. Subsequent calls will find that the key has a value in the dictionary representing the results that have already been calculated, so it just returns those previous results. The net effect is that you don't waste time finding results that you already know.
一点粗略的JavaScript例子:
A little crude JavaScript example:
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;
}
详细介绍,甚至还包含一个通用的 memoize
JS函数用于任何其他功能。
This link goes into more detail, and even includes a generic memoize
JS function that could be used for any other function.
这篇关于真实世界的javascript中的memoization示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!