-
-
Notifications
You must be signed in to change notification settings - Fork 235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
设计LRU缓存结构 #272
Comments
// Vue3的keepalive组件就用了这个LRU管理组件的缓存
var LRUCache = function (capacity) {
this.map = new Map()
this.capacity = capacity
}
LRUCache.prototype.get = function (key) {
if (this.map.has(key)) {
let value = this.map.get(key)
// 重新set,相当于更新到 map最后
this.map.delete(key)
this.map.set(key, value)
return value
}
return -1
}
LRUCache.prototype.put = function (key, value) {
// 如果有,就删了再赋值
if (this.map.has(key)) {
this.map.delete(key)
}
this.map.set(key, value)
// 判断是不是容量超了,淘汰机制
if (this.map.size > this.capacity) {
this.map.delete(this.map.keys().next().value)
}
} |
思考:有没有考虑过LRU算法实现中为什么使用map,它的好处是什么?对于LRU算法,是get使用频率更高还是put使用频率更高?为什么?LRU算法的使用场景? —— 莉莉丝日常实习面试 |
//Least Recently Used(最近最少使用) 缓存淘汰算法
//此算法是简单版,如果要进一步优化时间复杂度,需要使用到双向链表
//使用map的原因:利用map的有序性,因为map.keys()返回的是一个迭代器,
//每次调用next()都是按照顺序获取map集合的键
class LRUCache {
constructor(capacity) {
this.cache = new Map()
this.capacity = capacity
}
get(key) {
if (!this.cache.has(key)) return -1
const value = this.cache.get(key)
//删除之前的记录,重新set到map集合最后
this.cache.delete(key)
this.cache.set(key, value)
return value
}
set(key, value) {
if (this.cache.has(key)) {
this.cache.delete(key)
}
if (this.cache.size >= this.capacity) {
//淘汰最久没使用的记录,iterator.next().value就是map集合的第一个键,也就是对应最久没使用的缓存
const iterator = this.cache.keys()
this.cache.delete(iterator.next().value)
}
this.cache.set(key, value)
}
}
const lruCache = new LRUCache(2)
lruCache.set('a', 'ysy')
lruCache.set('b', 'dzq')
lruCache.get('a')
lruCache.set('c', 'zbc')
console.log(lruCache.get('a')) //ysy
lruCache.set('a', 'ysy')
lruCache.set('b', 'dzq')
lruCache.set('c', 'zbc')
console.log(lruCache.get('a')) //-1 |
map存储的时候有顺序,实现了Iterator接口 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
设计LRU(最近最少使用)缓存结构,可参考如下模板
The text was updated successfully, but these errors were encountered: