当前位置:网站首页>Implementing expired localstorage cache with lazy deletion and scheduled deletion
Implementing expired localstorage cache with lazy deletion and scheduled deletion
2022-07-04 09:25:00 【Wanmao Society】
localStorage brief introduction
Use localStorage The data of key value pairs can be stored in the browser . Often and localStorage Also mentioned is sessionStorage, Both of them can store the data of key value pairs in the browser . But the difference between them is : Stored in localStorage The data can be kept for a long time ; And when the page session ends ( That is, when the page is closed ) when , Stored in sessionStorage The data will be cleared .
Another thing to note ,localStorage Key value pairs in are always stored as strings , And can only access the data under the current domain name , Can't cross domain access .
localStorage Method
Can pass setItem
Method adds a key value pair to the data , such as :
localStorage.setItem('name', 'OneMore');
Copy code
If the key already exists , Then the value corresponding to the key will be overwritten . You can also use getItem
Method to read the value data of the corresponding key , such as :
var name = localStorage.getItem('name');
Copy code
have access to removeItem
Method to remove the corresponding key , such as :
localStorage.removeItem('name');
Copy code
You can also use clear
Method to remove all key value pair data under the current domain name , such as :
localStorage.clear();
Copy code
Expirable localStorage cache
As mentioned above ,localStorage It can only be used to save the data of the whole website for a long time , Saved data has no expiration time , Until you delete it manually . Therefore, we should realize the expiration localStorage The focus of caching is : How to clean up expired cache ?
Lazy deletion
Inert deletion means , After a key value expires , The key value will not be deleted immediately , But wait until the next time it is used , Will be checked to expire , Only then can it be deleted . Let's make it simple :
var lsc = (function (self) {
var prefix = 'one_more_lsc_'
/** * Add a key value pair to the data * @param key key * @param val value * @param expires Expiration time , The unit is in seconds */
self.set = function (key, val, expires) {
key = prefix + key;
val = JSON.stringify({'val': val, 'expires': new Date().getTime() + expires * 1000});
localStorage.setItem(key, val);
};
/** * Read the value data of the corresponding key * @param key key * @returns {null|*} The value of the corresponding bond */
self.get = function (key) {
key = prefix + key;
var val = localStorage.getItem(key);
if (!val) {
return null;
}
val = JSON.parse(val);
if (val.expires < new Date().getTime()) {
localStorage.removeItem(key);
return null;
}
return val.val;
};
return self;
}(lsc || {}));
Copy code
The above code has realized expirable through lazy deletion localStorage cache , But there are also obvious shortcomings : If one key Has not been used , Even if it has expired, it will always be stored in localStorage. In order to make up for such shortcomings , We introduce another strategy to clean up expired caches .
Delete regularly
Scheduled deletion refers to , Delete every other period of time , And by limiting the number and frequency of deletion operations , To reduce the number of delete operations CPU Long term occupation of . On the other hand, scheduled deletion also effectively reduces the impact of lazy deletion on localStorage Waste of space .
Perform scheduled deletion every second , The operation is as follows :
- Random test 20 With expiration time set key.
- Delete all found expired key.
- If you delete key exceed 5 One repeats step 1, Until repeated 500 Time .
The specific implementation is as follows :
var lsc = (function (self) {
var prefix = 'one_more_lsc_'
var list = [];
// initialization list
self.init = function () {
var keys = Object.keys(localStorage);
var reg = new RegExp('^' + prefix);
var temp = [];
// Traverse all of localStorage All in key
for (var i = 0; i < keys.length; i++) {
// Find the cache that can expire key
if (reg.test(keys[i])) {
temp.push(keys[i]);
}
}
list = temp;
};
self.init();
self.check = function () {
if (!list || list.length == 0) {
return;
}
var checkCount = 0;
while (checkCount < 500) {
var expireCount = 0;
// Random test 20 With expiration time set key
for (var i = 0; i < 20; i++) {
if (list.length == 0) {
break;
}
var index = Math.floor(Math.random() * list.length);
var key = list[index];
var val = localStorage.getItem(list[index]);
// from list Delete the inert deleted key
if (!val) {
list.splice(index, 1);
expireCount++;
continue;
}
val = JSON.parse(val);
// Delete all found expired key
if (val.expires < new Date().getTime()) {
list.splice(index, 1);
localStorage.removeItem(key);
expireCount++;
}
}
// If you delete key No more than 5 One jumps out of the loop
if (expireCount <= 5 || list.length == 0) {
break;
}
checkCount++;
}
}
// Perform scheduled deletion every second
window.setInterval(self.check, 1000);
return self;
}(lsc || {}));
Copy code
Complete source code and use examples
The complete source code and usage examples have been uploaded to my GitHub(github.com/heihaozi/Lo…
summary
A strategy may have its own shortcomings , In order to avoid the corresponding shortcomings , We can use a variety of strategies , Develop strengths and avoid weaknesses to get a near perfect solution .
边栏推荐
- C language - Introduction - Foundation - syntax - [identifier, keyword, semicolon, space, comment, input and output] (III)
- [on February 11, 2022, the latest and most fully available script library collection of the whole network, a total of 23]
- Awk from getting started to digging in (11) detailed explanation of awk getline function
- 2022-2028 global edible probiotic raw material industry research and trend analysis report
- Research and investment strategy report of China's electronic hydrogen peroxide industry (2022 Edition)
- Explanation of closures in golang
- Tkinter Huarong Road 4x4 tutorial II
- Report on the development trend and prospect trend of high purity zinc antimonide market in the world and China Ⓕ 2022 ~ 2027
- 2022-2028 global optical transparency industry research and trend analysis report
- Sequence model
猜你喜欢
How do microservices aggregate API documents? This wave of show~
Clion console output Chinese garbled code
2022-2028 global visual quality analyzer industry research and trend analysis report
C language - Introduction - Foundation - syntax - [main function, header file] (II)
C language - Introduction - Foundation - syntax - [operators, type conversion] (6)
Function comparison between cs5261 and ag9310 demoboard test board | cost advantage of cs5261 replacing ange ag9310
Reload CUDA and cudnn (for tensorflow and pytorch) [personal sorting summary]
How does idea withdraw code from remote push
C语言-入门-基础-语法-[变量,常亮,作用域](五)
2022-2028 global edible probiotic raw material industry research and trend analysis report
随机推荐
Relationship and operation of random events
【LeetCode 42】501. Mode in binary search tree
Launpad | 基础知识
LinkedList in the list set is stored in order
In depth investigation and Strategic Research Report on China's motion controller Market (2022 Edition)
2022-2028 global industrial gasket plate heat exchanger industry research and trend analysis report
如何编写单元测试用例
Implementation principle of redis string and sorted set
[on February 11, 2022, the latest and most fully available script library collection of the whole network, a total of 23]
Global and Chinese PCB function test scale analysis and development prospect planning report Ⓑ 2022 ~ 2027
How should PMP learning ideas be realized?
Global and Chinese market of sampler 2022-2028: Research Report on technology, participants, trends, market size and share
地平线 旭日X3 PI (一)首次开机细节
Launpad | basic knowledge
Leetcode topic [array] - 121 - the best time to buy and sell stocks
Mac platform forgets the root password of MySQL
China electronic grade sulfur trioxide Market Forecast and investment strategy report (2022 Edition)
The old-fashioned synchronized lock optimization will make it clear to you at once!
Latex download installation record
2022-2028 global strain gauge pressure sensor industry research and trend analysis report