js storage 存储大小测试

发布时间 2023-05-19 21:11:29作者: 万物有序
 1 <script>
 2     function env(strategy) {
 3         const _strategy = window[strategy];
 4         function getStr(size) {
 5             return Array(size + 1).join("1");
 6         }
 7 
 8         function test(pieces, size) {
 9             let count = 0,
10                 piece = pieces.shift(),
11                 trySize = size;
12             if (pieces.length) {
13                 try {
14                     while (true) {
15                         trySize = size + (count + 1) * piece;
16                         _strategy.setItem(`${strategy}:test`, getStr(trySize));
17                         count++;
18                     }
19                 } catch (err) {
20                     return test(pieces, trySize - piece);
21                 }
22             } else {
23                 let K = size / 2 ** 10,
24                     M = K / 2 ** 10;
25                 return { K, M };
26             }
27         }
28 
29         _strategy.clear();
30 
31         const { K, M } = test(
32             [20, 18, 16, 13, 10].map((level) => 2 ** level), // 预估一个存储梯度
33             0,
34         );
35 
36         _strategy.clear();
37 
38         console.log(`${strategy}大致可存储 ${K}K,合约 ${M}M`);
39     }
40 
41     env("localStorage");
42     env("sessionStorage");
43 </script>