Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much space does the localstorage key itself take up?

Lets say i create a localstorage key and give it an empty string. Does the name of the keyitem take up the same amount of space as the value would per character?

for instance does

localStorage.setItem("keyitem","") 
//Equal the space of this other one under?
localStorage.setItem("key","item");

Also, does the amount of keys matter? for instance

localStorage.setItem("key","");
//Equal the amount of storage as the 3 under combined? 
localStorage.setItem("k","");
localStorage.setItem("o","");
localStorage.setItem("h","");
like image 848
Mattias Avatar asked Apr 29 '15 13:04

Mattias


2 Answers

I found a function once to calculate the size of the localStorage and sessionStorage objects, but I can't remember where I found it.

Here's the code:

Storage.prototype.size = function(units) {
    'use strict';
    units = units ? units.toUpperCase() : 'MB';
    var size = unescape(encodeURIComponent(JSON.stringify(this))).length;
    switch (units) {
        case 'B': return [size,'B'].join(' ');
        case 'KB': return [+(size / 1024).toFixed(3),'KB'].join(' ');
        default: return [+(size / 1024 / 1024).toFixed(3),'MB'].join(' ');
    }
};

I decided to go ahead and run some tests in various browsers.

Firefox (37.0.2):

Firefox console output

Chrome (42.0.2311.90 m):

Chrome console output

IE 11 (11.0.9600.17420):

IE Console Output

Opera (29.0.1795.47):

Opera console output

So it looks like FireFox, Chrome, and Opera (probably Safari as well, but I don't have that) all have the same behavior, and keys take up far more space than their values.

In IE (good old IE...), the implementation is executed in a way such that it doesn't matter how you store something.

like image 130
RevanProdigalKnight Avatar answered Oct 22 '22 07:10

RevanProdigalKnight


Does the name of the keyitem take up the same amount of space as the value would per character?

No, it is not necessary. The amount of space taken by key could be more than the amount of space taken by value. But together the space taken by key and value should be approx 5MB(although this differs with browser as it is browser dependent)

You can use this code to test:

localStorage.clear();
localStorage.setItem(new Array(5e6).join(' '),'');
localStorage.key(0).length;

Output on Chrome for the above test:

enter image description here

So as long as it comes under 5MB(which is mostly the upper limit for most browsers) your key can have any length

like image 35
Rahul Tripathi Avatar answered Oct 22 '22 07:10

Rahul Tripathi