缓存和记忆化有什么区别?
我想知道缓存
和记忆
之间的实际区别是什么。
在我看来,两者都涉及避免通过存储数据来重复调用函数来获取数据。
两者的核心区别是什么?
I would like to know what the actual difference between caching
and memoization
is.
As I see it, both involve avoiding repeated function calls to get data by storing it.
What's the core difference between the two?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
记忆化是一种特定形式的缓存,涉及根据函数的参数缓存函数的返回值。
缓存是一个更通用的术语;例如,HTTP 缓存是缓存,但不是记忆。
维基百科说:
Memoization is a specific form of caching that involves caching the return value of a function based on its parameters.
Caching is a more general term; for example, HTTP caching is caching but not memoization.
Wikipedia says:
正如我所看到的,“记忆化”是“缓存确定性函数的结果”,在给定相同的函数和输入的情况下可以随时重现。
“缓存”基本上包括任何输出缓冲策略,无论源值在给定时间是否可再现。事实上,缓存也用于指输入缓冲策略,例如磁盘或内存上的写入缓存。所以它是一个更通用的术语。
As I have seen them used, "memoization" is "caching the result of a deterministic function" that can be reproduced at any time given the same function and inputs.
"Caching" includes basically any output-buffering strategy, whether or not the source value is reproducible at a given time. In fact, caching is also used to refer to input buffering strategies, such as the write-cache on a disk or memory. So it is a much more general term.
我认为术语“缓存”通常用于存储 IO 操作的结果,或者基本上是从外部获取的任何数据(文件、网络、数据库查询)。术语记忆通常适用于存储您自己的计算结果,例如在动态编程的上下文中。
I think term caching is usually used when you store results of IO operations, or basically any data that is coming to you from the outside (files, network, db queries). Term memoization usually applies to storing results of your own computations, for example in the context of dynamic programming.
记忆化是缓存确定性函数结果的一种特殊形式。这意味着在函数外部缓存结果不是记忆化,因为函数在计算新结果(尚未在缓存中)时必须改变缓存,因此它不再是(纯)函数。记忆化通常意味着将缓存作为附加参数传递(在辅助函数中)。记忆化将优化需要多次计算单次访问值的函数。缓存将优化使用相同参数多次调用的函数。换句话说,Memoization 会优化第一次访问,而缓存是否只会优化重复访问。
Memoization is a special form of caching the result of a deterministic function. This means that caching the result outside the function is not memoization because the function would have to mutate the cache when computing a new result (not already in the cache) so it would not be a (pure) function anymore. Memoization generally implies passing the cache as an additional argument (in an helper function). Memoization will optimize functions that need to compute values several times for a single access. Caching will optimize functions that are called several times with the same parameters. In other words, Memoization will optimize the first access whether caching will only optimize recurrent accesses.
我想补充一下其他很好的答案,记忆化也称为制表。我认为对于那些学习什么是记忆化和缓存的人来说,了解这个术语也很重要。
I would like to add to the other great answers that memoization is also known as tabling. I think it is also important to know that term for those who learn what memoization and caching are.