如何在 elisp 中实现过期 LRU 缓存?
我的数据由以下三个部分组成:
a_path
a_key
a_value =
f
(a_path, a_key)
a_value
计算起来很昂贵,所以我不想经常计算它。在理想的世界中,只有当情况发生变化时才会发生这种情况。因此,我对此缓存的要求如下:
- 具有可配置最大大小的 LRU 缓存
- Keyed on
(a_path, a_key)
- 能够根据年龄使条目过期(例如,每小时左右重新计算一次)
- 能力使基于
expiry_func
(a_path, a_key)
的条目过期
我的谷歌搜索在这里失败了;即使在搜索“elisp LRU cache”时,我也发现了很多 Java 站点。
I have data that consists of the following three components:
a_path
a_key
a_value =
f
(a_path, a_key)
a_value
is expensive to calculate, so I want to calculate it infrequently. In an ideal world, that would be only when it's going to change. So, my requirements for this cache are as follows:
- LRU cache with configurable maximum size
- Keyed on
(a_path, a_key)
- Ability to expire an entry based on age (recalculate every hour or so, for example)
- Ability to expire an entry based on
expiry_func
(a_path, a_key)
My googling has failed me here; I find a lot of Java sites even when searching for "elisp LRU cache".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是您想要的大部分内容:固定大小的最近最少使用的缓存,具有 O(1) 查找、O(1) 插入和 O(1) 删除。
让所有这些操作都达到 O(1) 有点棘手,因此这个实现稍微复杂一些。我将哈希表(用于快速查找)与双向链接的项目列表(用于快速删除、重新排序和查找最旧的元素)结合起来。
对于以对为键的应用程序,您可能需要向
lru-create
提供:test 'equal
。或者参见定义哈希比较如果你需要一些特别的东西。我会让你弄清楚如何进行基于时间的到期;从这里开始应该很简单。
(如果有人知道一种更简单的方法来实现这一点,同时保持操作在恒定时间内运行,我将非常有兴趣看到它。)
Here's most of what you want: a fixed-size least-recently-used cache with O(1) lookup, O(1) insertion, and O(1) deletion.
It's slightly tricky to get all of these operations to be O(1), hence this slightly elaborate implementation. I combine a hash-table (for fast lookup) with a doubly-linked list of items (for fast removal, re-ordering, and finding the oldest element).
For your application that's keyed on pairs, you probably want to supply
:test 'equal
tolru-create
. Or see Defining Hash Comparisons if you need something special.I'll let you figure out how to do the time-based expiry; it should be straightforward from here.
(If anyone knows a simpler way to implement this while keeping the operations running in constant time, I'd be very interested to see it.)