Answers:
在JavaScript控制台(单行版本)中执行以下代码段:
var _lsTotal=0,_xLen,_x;for(_x in localStorage){ if(!localStorage.hasOwnProperty(_x)){continue;} _xLen= ((localStorage[_x].length + _x.length)* 2);_lsTotal+=_xLen; console.log(_x.substr(0,50)+" = "+ (_xLen/1024).toFixed(2)+" KB")};console.log("Total = " + (_lsTotal / 1024).toFixed(2) + " KB");
多行阅读相同的代码
var _lsTotal = 0,
_xLen, _x;
for (_x in localStorage) {
if (!localStorage.hasOwnProperty(_x)) {
continue;
}
_xLen = ((localStorage[_x].length + _x.length) * 2);
_lsTotal += _xLen;
console.log(_x.substr(0, 50) + " = " + (_xLen / 1024).toFixed(2) + " KB")
};
console.log("Total = " + (_lsTotal / 1024).toFixed(2) + " KB");
或将此文本添加到书签的“位置”字段中以方便使用
javascript: var x, xLen, log=[],total=0;for (x in localStorage){if(!localStorage.hasOwnProperty(x)){continue;} xLen = ((localStorage[x].length * 2 + x.length * 2)/1024); log.push(x.substr(0,30) + " = " + xLen.toFixed(2) + " KB"); total+= xLen}; if (total > 1024){log.unshift("Total = " + (total/1024).toFixed(2)+ " MB");}else{log.unshift("Total = " + total.toFixed(2)+ " KB");}; alert(log.join("\n"));
PS片段根据注释中的请求进行更新。现在,计算包括密钥本身的长度。每个长度都乘以2,因为javascript中的char存储为UTF-16(占用2个字节)
PPS应该在Chrome和Firefox中均可使用。
var t = 0; for(var x in localStorage) { t += (x.length + localStorage[x].length) * 2; } console.log(t/1024+ " KB");
var _lsTotal = 0, _xLen, _x; for (_x in localStorage) { _xLen = (((localStorage[_x].length || 0) + (_x.length || 0)) * 2); _lsTotal += _xLen; console.log(_x.substr(0, 50) + " = " + (_xLen / 1024).toFixed(2) + " KB") }; console.log("Total = " + (_lsTotal / 1024).toFixed(2) + " KB");
_x
会破坏它。只需删除下划线。
在上面@Shourav所说的基础上,我编写了一个小函数,该函数应该准确地捕获所有localStorage
密钥(对于当前域)并计算组合大小,以便您确切知道localStorage
对象占用了多少内存:
var localStorageSpace = function(){
var allStrings = '';
for(var key in window.localStorage){
if(window.localStorage.hasOwnProperty(key)){
allStrings += window.localStorage[key];
}
}
return allStrings ? 3 + ((allStrings.length*16)/(8*1024)) + ' KB' : 'Empty (0 KB)';
};
我的退货: "30.896484375 KB"
这是一个简单的示例,说明如何执行此方法,该方法应适用于每种浏览器
alert(1024 * 1024 * 5 - unescape(encodeURIComponent(JSON.stringify(localStorage))).length);
希望这可以帮助某人。
因为jsfiddle上的Jas-example对我不起作用,所以我提出了这个解决方案。(感谢Serge Seletskyy和Shourav在下面的代码中使用的位)
以下是可用于测试localStorage可用空间和(如果ls中已有任何键)剩余空间的功能。
这有点蛮力,但它几乎可以在除Firefox外的所有浏览器中使用。在台式机FF中,它需要花一些时间(4-5分钟)才能完成,而在Android上它只会崩溃。
该功能的下方是我在不同平台上的不同浏览器中完成的测试的简短摘要。请享用!
function testLocalStorage() {
var timeStart = Date.now();
var timeEnd, countKey, countValue, amountLeft, itemLength;
var occupied = leftCount = 3; //Shurav's comment on initial overhead
//create localStorage entries until localStorage is totally filled and browser issues a warning.
var i = 0;
while (!error) {
try {
//length of the 'value' was picked to be a compromise between speed and accuracy,
// the longer the 'value' the quicker script and result less accurate. This one is around 2Kb
localStorage.setItem('testKey' + i, '11111111112222222222333333333344444444445555555555666661111111111222222222233333333334444444444555555555566666');
} catch (e) {
var error = e;
}
i++;
}
//if the warning was issued - localStorage is full.
if (error) {
//iterate through all keys and values to count their length
for (var i = 0; i < localStorage.length; i++) {
countKey = localStorage.key(i);
countValue = localStorage.getItem(localStorage.key(i));
itemLength = countKey.length + countValue.length;
//if the key is one of our 'test' keys count it separately
if (countKey.indexOf("testKey") !== -1) {
leftCount = leftCount + itemLength;
}
//count all keys and their values
occupied = occupied + itemLength;
}
;
//all keys + values lenght recalculated to Mb
occupied = (((occupied * 16) / (8 * 1024)) / 1024).toFixed(2);
//if there are any other keys then our 'testKeys' it will show how much localStorage is left
amountLeft = occupied - (((leftCount * 16) / (8 * 1024)) / 1024).toFixed(2);
//iterate through all localStorage keys and remove 'testKeys'
Object.keys(localStorage).forEach(function(key) {
if (key.indexOf("testKey") !== -1) {
localStorage.removeItem(key);
}
});
}
//calculate execution time
var timeEnd = Date.now();
var time = timeEnd - timeStart;
//create message
var message = 'Finished in: ' + time + 'ms \n total localStorage: ' + occupied + 'Mb \n localStorage left: ' + amountLeft + "Mb";
//put the message on the screen
document.getElementById('scene').innerText = message; //this works with Chrome,Safari, Opera, IE
//document.getElementById('scene').textContent = message; //Required for Firefox to show messages
}
正如上面所承诺的,可以在不同的浏览器中进行一些测试:
GalaxyTab 10.1
iPhone 4s iOS 6.1.3
MacBook Pro OSX 1.8.3(Core 2 Duo 2.66 8Gb内存)
iPad 3 iOS 6.1.3
Windows 7 -64b(Core 2 Duo 2.93 6Gb内存)
赢8(平行八下)
array.forEach()
在您的代码中发现了,因为我知道它在IE中不存在,您是自己实现吗?您如何衡量其对总延迟的贡献?
forEach()
。不,我本人并没有实现它,所以我用了库存Array.prototype.forEach()
。根据Mozilla开发人员网络(又称 IE9的MDN),它具有本机支持。
Array.prototype.forEach()
如果以后我的项目不支持早期的IE版本,我将尽可能多地使用。
while
循环分为两部分,第一部分类似于stackoverflow.com/a/3027249/1235394,该部分以指数级增长的数据块填充localStorage,然后第二部分为固定大小的小块完全填充存储。测试页:jsfiddle.net/pqpps3tk/1
您可以使用Blob函数获取当前本地存储数据的大小。这可能不会在旧的浏览器工作,检查的支持new Blob
,并Object.values()
在caniuse。
例:
return new Blob(Object.values(localStorage)).size;
Object.values()将localStorage对象转换为数组。Blob将数组转换为原始数据。
Blob
不会将字符串编码限制为UTF-16,因此这实际上可能是最可靠的方法。new Blob(['X']).size;
= 1,而new Blob(['☃']).size
(U + 2603 /雪人字符)==> 3.基于的解决方案String.prototype.length
不考虑这一点(使用“字符”处理),而存储配额/限制可能会考虑(使用字节处理),我可以想象例如,在存储非英语/ ASCII字符时,这会引起意外。
您可以通过以下方法计算本地存储:
function sizeofAllStorage(){ // provide the size in bytes of the data currently stored
var size = 0;
for (i=0; i<=localStorage.length-1; i++)
{
key = localStorage.key(i);
size += lengthInUtf8Bytes(localStorage.getItem(key));
}
return size;
}
function lengthInUtf8Bytes(str) {
// Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
var m = encodeURIComponent(str).match(/%[89ABab]/g);
return str.length + (m ? m.length : 0);
}
console.log(sizeofAllStorage());
最后以字节为单位的大小将被记录在浏览器中。
我会使用@tennisgen的代码来获取所有内容并计算内容,但是我自己计算密钥:
var localStorageSpace = function(){
var allStrings = '';
for(var key in window.localStorage){
allStrings += key;
if(window.localStorage.hasOwnProperty(key)){
allStrings += window.localStorage[key];
}
}
return allStrings ? 3 + ((allStrings.length*16)/(8*1024)) + ' KB' : 'Empty (0 KB)';
};
我解决此问题的方法是创建用于找出本地存储中已用空间和剩余空间的函数,然后创建一个调用这些函数以确定最大存储空间的函数。
function getUsedSpaceOfLocalStorageInBytes() {
// Returns the total number of used space (in Bytes) of the Local Storage
var b = 0;
for (var key in window.localStorage) {
if (window.localStorage.hasOwnProperty(key)) {
b += key.length + localStorage.getItem(key).length;
}
}
return b;
}
function getUnusedSpaceOfLocalStorageInBytes() {
var maxByteSize = 10485760; // 10MB
var minByteSize = 0;
var tryByteSize = 0;
var testQuotaKey = 'testQuota';
var timeout = 20000;
var startTime = new Date().getTime();
var unusedSpace = 0;
do {
runtime = new Date().getTime() - startTime;
try {
tryByteSize = Math.floor((maxByteSize + minByteSize) / 2);
localStorage.setItem(testQuotaKey, new Array(tryByteSize).join('1'));
minByteSize = tryByteSize;
} catch (e) {
maxByteSize = tryByteSize - 1;
}
} while ((maxByteSize - minByteSize > 1) && runtime < timeout);
localStorage.removeItem(testQuotaKey);
if (runtime >= timeout) {
console.log("Unused space calculation may be off due to timeout.");
}
// Compensate for the byte size of the key that was used, then subtract 1 byte because the last value of the tryByteSize threw the exception
unusedSpace = tryByteSize + testQuotaKey.length - 1;
return unusedSpace;
}
function getLocalStorageQuotaInBytes() {
// Returns the total Bytes of Local Storage Space that the browser supports
var unused = getUnusedSpaceOfLocalStorageInBytes();
var used = getUsedSpaceOfLocalStorageInBytes();
var quota = unused + used;
return quota;
}
除了在这里投票最多的@serge答案外,还需要考虑密钥的大小。以下代码将添加存储在其中的密钥的大小localStorage
var t = 0;
for (var x in localStorage) {
t += (x.length + localStorage[x].length) * 2;
}
console.log((t / 1024) + " KB");
undefined
该商品length
,因此我在添加内容中添加了一个条件t += (x.length + (this.storage[x].length ? this.storage[x].length : 0)) * 2;
。
//内存被键和值占用,因此更新了代码。
var jsonarr=[];
var jobj=null;
for(x in sessionStorage) // Iterate through each session key
{
jobj={};
jobj[x]=sessionStorage.getItem(x); //because key will also occupy some memory
jsonarr.push(jobj);
jobj=null;
}
//https://developer.mozilla.org/en/docs/Web/JavaScript/Data_structures
//JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values.
var size=JSON.stringify(jsonarr).length*2; //16-bit that's why multiply by 2
var arr=["bytes","KB","MB","GB","TB"]; // Define Units
var sizeUnit=0;
while(size>1024){ // To get result in Proper Unit
sizeUnit++;
size/=1024;
}
alert(size.toFixed(2)+" "+arr[sizeUnit]);
是的,这个问题是10年前问的。但是对于那些感兴趣的人(像我一样,因为我正在构建一个脱机文本编辑器以将数据存储在本地存储中)并精于编程,因此可以使用以下简单方法:
var warning = 1;
var limit = 2000000; //2 million characters, not really taking in account to bytes but for tested ammounts of characters stored
setInterval(function() {
localStorage["text"] = document.getElementById("editor").innerHTML; //gets text and saves it in local storage under "text"
if(localStorage["text"].length > limit && warning == 1){
alert("Local Storage capacity has been filled");
warning = 2; //prevent a stream of alerts
}
}, 1000);
//setInterval function saves and checks local storage
获取已满存储量的最佳方法是查看站点设置(例如,如果您将图像存储在本地存储中)。至少在chrome中,您可以看到使用的字节数(即:1222字节)。但是,上面已经提到了用js查看填充的本地存储的最佳方法,因此请使用它们。