LRU算法在接口缓存Cache中的应用

588 阅读3分钟

翻了翻以前的代码,突然看到之前设计接口缓存的时候用到的一个小技巧,觉得挺有意思,分享一下。

古有谈缓存色变,而在早期前端开发心中大概有谈缓存色变的缘由。很多更改都不能立刻生效,造成了用户的体验以及测试验收过不去的一道坎。不可否认的是,缓存是有害的。但是不可否认的是,他真的很快啊。就像~~~讨厌一个人有千千万万个理由,喜欢一个人只要一个理由就够啦。然而,落到实处,我们要把所有的接口返回都缓存起来吗?在时间复杂度和空间度中做取舍话,大概只能说世界上哪有两全之法,有的只是取舍罢了。回到正题,什么事LRU算法呢?

LRU是Least Recently Used的缩写,即最近最少使用,是一种常用的页面置换算法,选择最近最久未使用的页面予以淘汰。 该算法赋予每个页面一个访问字段,用来记录一个页面自上次被访问以来所经历的时间t,当须淘汰一个页面时,选择现有页面中其t 值最大的,即最近最少使用的页面予以淘汰。

通俗的举例来说,假设我们有一个玩具摊位,可以向顾客展示小玩具,但是摊位大小有限,我们不能把所有的玩具都摆在摊位上,所以我们就把大部分的玩具都放在了仓库里。

image.png

如果有顾客来问,我们就去仓库把那个玩具拿出来,摆在摊位上。

image.png

因为最上面的那个位置最显眼,所以我们想总是把最新拿出来的玩具放在那

image.png

但是摊位大小有限,很快就摆满了,如果这时又来了顾客想看新玩具。

image.png

我们只能把最下面的玩具拿回仓库(因为最下面的位置相对没那么受欢迎),腾出一个位置来放新玩具

image.png

如果顾客想看的玩具就在摊位上,我们就可以直接展示这个玩具,同时把它放到最上面的位置(有人问说明它受欢迎嘛),其他的玩具就要挪挪位置了。

image.png

回到计算机上,时间复杂度是O(n)的话只能是数据结构中链表了。无奈原声JS中没有像Java一样原声提供。这边用Map的奇技淫巧实现一下

/**
 * @param {number} capacity
 */
var LRUCache = function(capacity) {
    this.cache = new Map();
    this.capacity = capacity;
};

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function(key) {
    if(!this.cache.has(key)) return -1;
    
    const v = this.cache.get(key);
    this.cache.delete(key);
    this.cache.set(key, v);
    return this.cache.get(key);
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function(key, value) {
    if (this.cache.has(key)) {
      this.cache.delete(key);
    }
    this.cache.set(key, value);
    if (this.cache.size > this.capacity) {
      this.cache.delete(this.cache.keys().next().value);  // keys().next().value returns first item's key
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * var obj = new LRUCache(capacity)
 * var param_1 = obj.get(key)
 * obj.put(key,value)
 */

以下是模拟实现

class DoubleLinkedListNode {
    constructor(key, value) {
        this.key = key
        this.value = value
        this.prev = null
        this.next = null
    }
}

class LRUCache {
    constructor(capacity) {
        this.capacity = capacity
        this.usedSpace = 0
        // Mappings of key->node.
        this.hashmap = {}
        this.dummyHead = new DoubleLinkedListNode(null, null)
        this.dummyTail = new DoubleLinkedListNode(null, null)
        this.dummyHead.next = this.dummyTail
        this.dummyTail.prev = this.dummyHead
    }

    _isFull() {
        return this.usedSpace === this.capacity
    }

    _removeNode(node) {
        node.prev.next = node.next
        node.next.prev = node.prev
        node.prev = null
        node.next = null
        return node
    }

    _addToHead(node) {
        const head = this.dummyHead.next
        node.next = head
        head.prev = node
        node.prev = this.dummyHead
        this.dummyHead.next = node
    }

    get(key) {
        if (key in this.hashmap) {
            const node = this.hashmap[key]
            this._addToHead(this._removeNode(node))
            return node.value
        }
        else {
            return -1
        }
    }

    put(key, value) {
        if (key in this.hashmap) {
            // If key exists, update the corresponding node and move it to the head.
            const node = this.hashmap[key]
            node.value = value
            this._addToHead(this._removeNode(node))
        }
        else {
        // If it's a new key.
            if (this._isFull()) {
                // If the cache is full, remove the tail node.
                const node = this.dummyTail.prev
                delete this.hashmap[node.key]
                this._removeNode(node)
                this.usedSpace--
            }
            // Create a new node and add it to the head.
            const node = new DoubleLinkedListNode(key, value)
            this.hashmap[key] = node
            this._addToHead(node)
            this.usedSpace++
        }
    }
}

通过LRU将较少频率使用的搜索参数和结果淘汰,每次保留更新最新的返回结果,大概也不是为折中的好办法吧。