当我们打开一个网页的时候,它回去查询浏览器缓存,看是否有要请求的文件,如果储存,就会返回缓存的文件。如果不存在,才会请求服务器。
这就是 浏览器缓存
浏览器缓存是一种在本地保存资源的副本,他的大小是有限制的。当我们请求过多的时候,继续请求就需要缓存去确定哪些数据应该被保留,哪些数据应该被删除。
这就是 浏览器缓存淘汰策略
常见的浏览器淘汰策略有以下几种
- 先进先出(FIFO)
- 最少使用(LFU)
- 最近最少使用(LRU)
JS实现FIFO
class FIFOCache {
constructor(limit) {
this.limit = limit || [];
this.map = {};
this.keys = [];
}
set(key, value) {
let map = this.map;
let keys = this.keys;
if (!Object.prototype.hasOwnProperty.call(map, key)) {
if (keys.length === this.limit) {
delete map[keys.shift()];
}
keys.push(key);
}
map[key] = value;
}
get(key) {
return this.map[key];
}
}
JS实现LRU
vue的keep-alive就是使用的LRU
class LRUCache {
constructor(limit) {
this.cache = new Map();
this.limit = limit;
}
put(key, value) {
if (this.cache.has(key)) {
this.cache.delete(key);
} else if (this.cache.size >= this.limit) {
this.cache.delete(this.cache.keys().next().value);
}
this.cache.set(key, value);
}
get(key) {
if (this.cache.has(key)) {
let temp = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, temp);
return temp;
}
return -1;
}
}
网友评论