"LeastRecentlyUsedCache" (数据结构)
"LeastRecentlyUsedCache" (数据结构)
"LeastRecentlyUsedCache"
表示一个固定大小的缓存,其中的键和值为普通表达式.
更多信息
- 固定大小的缓存表存储可通过键来获取的值:
-
CreateDataStructure["LeastRecentlyUsedCache",capacity] 创建可存储 capacity 个值的新的空 "LeastRecentlyUsedCache" CreateDataStructure["LeastRecentlyUsedCache",elems] 创建一个包含 elems 的新 "LeastRecentlyUsedCache" CreateDataStructure["LeastRecentlyUsedCache",cache, f] 创建新的具有指定的逐出函数 f 的 "LeastRecentluUsedCache" Typed[x,"LeastRecentlyUsedCache"] 指定 x 的类型为 "LeastRecentlyUsedCache" - 对于类型为 "LeastRecentlyUsedCache" 的数据结构,可进行以下操作:
-
ds["Capacity"] ds 中最多可以存储多少个 key-value 对 时间:O(1) ds["Copy"] 返回 ds 的副本 时间:O(n) ds["EmptyQ"] 如果 ds 中没有任何 key-value 对则返回 True 时间:O(1) ds["Insert",keyvalue] 将 key 及关联的 value 的添加到 ds 中,如果从缓存中清除了某些内容则返回 True 时间:O(1) ds["KeyDrop",key] 从 ds 中删除 key 及其值 时间:O(1) ds["KeyDropAll"] 删除 ds 中所有的键及其值 时间:O(n) ds["KeyExistsQ",key] 如果 ds 中有 key 则返回 True 时间:O(1) ds["Keys"] 以列表形式返回 ds 中的键 时间:O(n) ds["Length"] ds 中存储的 key-value 对的数量 时间:O(1) ds["Lookup",key] 返回 ds 中存储的 key 的值并使此键成为最近使用的元素;如果没有找到该键则返回 Missing 对象 时间:O(1) ds["Lookup",key,defFun] 返回 ds 中存储的 key 的值并使此键成为最近使用的元素;如果没有找到该键则返回 defFun[key] 时间:O(1) ds["Peek"] 返回存储在 ds 中的最新的值 时间:O(1) ds["Peek",key] 返回 ds 中存储的 key 的值;不要将此键变为最近使用的元素 时间:O(1) ds["RemoveOldest"] 删除 ds 中最早的 key-value 对 时间:O(1) ds["Values"] 以列表形式返回 ds 中的值 时间:O(n) ds["Visualization"] 返回 ds 的可视化 时间:O(n) - 还支持以下函数:
-
dsi===dsj 如果 dsi 等于 dsj 则为 True FullForm[ds] ds 的完全形式 Information[ds] 关于 ds 的信息 InputForm[ds] ds 的输入形式 Normal[ds] 将 ds 转换成普通表达式 - 如果 "LeastRecentlyUsedCache" 已存储了最大数量的 key-value 数据对,任何新的插入操作都使最近最少使用的 key-value 对被清除掉.
范例
打开所有单元 关闭所有单元基本范例 (2)
可用 CreateDataStructure 创建新的 "LeastRecentlyUsedCache":
ds = CreateDataStructure["LeastRecentlyUsedCache", 3]ds["Length"]ds["Capacity"]ds["Insert", f[1] -> 1]ds["Length"]ds["KeyExistsQ", f[1]]ds["Lookup", f[1]]如果没有找到键,返回 Missing 对象:
ds["Lookup", f[2]]ds["Insert", f[2] -> 2];
ds["Insert", f[3] -> 3];
Normal[ds]ds["Lookup", f[1]];Normal[ds]ds["Insert", f[4] -> 4]表达式形式显示出一个 key-value 对从缓存中被清除:
Normal[ds]可视化 "LeastRecentlyUsedCache",显示最近使用的 key-value 对:
ds = CreateDataStructure["LeastRecentlyUsedCache", 3];
ds["Insert", f[1] -> 1];
ds["Insert", f[2] -> 2];
ds["Insert", f[3] -> 3];
ds["Visualization"]范围 (2)
信息 (1)
可用 CreateDataStructure 创建新的 "LeastRecentlyUsedCache":
ds = CreateDataStructure["LeastRecentlyUsedCache", 3]Information[ds]逐出 (1)
evictions = 0;
evicted = {};
trackEvictions =
Function[{key, val},
evictions++;
AppendTo[evicted, key -> val]
];创建新的 "LeastRecentlyUsedCache",容量为 2,并带有可跟踪逐出的函数:
ds = CreateDataStructure["LeastRecentlyUsedCache", 2, trackEvictions ]ds["Insert", 1 -> "one" ];
ds["Insert", 2 -> "two"];ds["Insert", 3 -> "three"]Normal[ds]evictionsevicted历史
2020年引入 (12.1)