2010-12-08 215 views
69

我目前正在开发一个将使用HTML5的localStorage的网站。我已阅读所有关于不同浏览器的大小限制。但是,我还没有看到如何找出localStorage实例的当前大小。 This question似乎表明JavaScript没有内置的显示给定变量大小的方法。 localStorage是否有我没见过的内存大小属性?有没有简单的方法来做到这一点,我失踪了?如何查找localStorage的大小

我的网站旨在允许用户在“离线”模式下输入信息,因此当存储器快满时能够给出警告非常重要。

+1

http://stackoverflow.com/questions/3027142/calculating-usage-of-localstorage-space – Adam 2010-12-08 19:46:50

回答

121

在Chrome控制台

var _lsTotal=0,_xLen,_x;for(_x in localStorage){_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){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")); 

附:片段根据评论中的请求进行更新。现在计算包括密钥本身的长度。 每个长度都乘以2,因为javascript中的char存储为UTF-16(占用2个字节)

-1
window.localStorage.remainingSpace 
+6

如上所述 - 这是一个IE-唯一属性。 – 2011-06-01 18:44:56

15

IE具有Storage对象的remainingSpace属性。其他浏览器目前没有平等。

我相信默认的空间量是5MB,尽管我没有亲自测试它。

+0

这是一个IE onlyproperty – 2014-09-29 20:19:35

+0

是每个站点的5 MB限制还是所有站点的总体限制? – divyenduz 2014-12-30 05:41:15

+0

@divyenduz每个站点,我认为 – Adam 2014-12-30 19:13:03

13

这里是如何做到这一点简单的example,并应与每个浏览器

alert(1024 * 1024 * 5 - unescape(encodeURIComponent(JSON.stringify(localStorage))).length); 
+0

你不需要一个* 8的地方吗? – 2014-09-23 20:57:21

+0

取决于不考虑的字符集(即utf8等) – 2014-09-24 11:18:59

+0

这是以字节或比特为单位给出大小吗? – JamesTheAwesomeDude 2015-11-23 14:58:57

1

随着规范去工作,一个字符串的每个字符是16位。

但随着铬(设置>内容设置>缓存&网站数据)检查告诉我们,开始的localStorage需要3KB(开销大小)

和存储的数据的大小遵循这种关系(精确到1KB的)
3 +((localStorage.x.length * 16)/(8 * 1024)) kB

其中localStorage.x是您的存储字符串。

10

希望这可以帮助某人。

因为jsfiddle上的Jas例子不适用于我,我想出了这个解决方案。 (感谢塞尔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

  • 傲垫1.7〜1130ms为5Mb
  • 火狐20.0(测试版20.0)坠毁两者
  • 铬25.0.1364.169〜22250ms/5Mb的
  • 天然(识别如Safari 4.0/Webkit534.30)〜995ms/5Mb的

iPhone 4S的iOS 6.1.3

  • 的Safari〜520ms/5Mb的
  • 作为HomeApp〜525ms/5Mb的
  • 因为iCab〜710ms/5MB

的MacBook Pro OSX 1.8.3(酷睿2 2.66 8GB存储)

  • 的Safari 6.0.3〜105ms/5MB的
  • 的Chrome 26.0.1410.43〜3400ms/5MB的
  • 火狐20.0 300150ms(!)/ 10Mb以下
(抱怨脚本运行后不久)

的iPad 3的iOS 6.1.3

  • 的Safari〜430ms/5Mb的
  • 因为iCab〜595ms/5MB

视窗7 -64b(酷睿2 2.93的6Gb存储器)

  • 的Safari 5.1.7〜80毫秒/ 5Mb的
  • 铬26.0.1410.43〜1220ms/5Mb
  • Firefox 20.0 228500ms(!)/ 10Mb(跑步后抱怨脚本长)
  • IE9〜17900ms /9.54Mb(如果有任何console.logs在代码中不行ķ直到DevTools打开)
  • 歌剧12.15〜4212ms /3.55Mb(这是在选择5Mb的,但歌剧询问很好,如果我们想要增加LS的量,遗憾的是它崩溃,如果测试连续进行了几次)

赢8(主管的Parallels 8)

  • IE10〜7850ms/9。54MB
32

去关一下@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"

5

您可以通过以下方法计算出你的localStorage:

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()); 

最后以字节为单位的大小将被记录在浏览器中。

3

我会用@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)'; 
    }; 
2

除了@哔叽的回答这是这里最投票,按键的大小需要考虑。下面的代码将添加存储在localStorage

var t = 0; 
for (var x in localStorage) { 
    t += (x.length + localStorage[x].length) * 2; 
} 
console.log((t/1024) + " KB"); 
0

//记忆键的大小双方键和值,更新的代码占据。

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]); 
1

我就对这个问题的方法是为找出使用空间,并留在本地存储和空间,然后调用这些函数来确定最大存储空间的函数创建函数。

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; 
}