Last Updated: February 25, 2016
· teddy

HTML5 Web Storage Custom Getter and Setter

HTML5 Web Storage offers a means to store string, string key-value pairs on the client's local drive. This means that any object will need to be stringified before adding to web storage.

If your application will be storing both plain strings and objects, then the question may arise as to whether it is better to have a getter and setter for each data type.

There are four things to consider:

  1. The increase in size using JSON when unnecessary

  2. The increase in computation time to stringify an object unnecessarily

  3. The increase in computation time to parse JSON

  4. The decrease in the number of lines of code to keep a common getter and setter

The increase in size will be 4 bytes for each plain text string, as they will be wrapped with quotes on each side. Since web storage is stored as UTF-16, so each character is 2 Bytes.

My bench test shows that there isn't a significant difference in the amount of time to store stings as JSON. For my application, this is done after an infrequently run 100-200ms operation, so adding a fraction of a millisecond was not noticeable.

The decrease in code, in my opinion, is the biggest benefit for commonality. I do not have to check which method I should run, and I do not have to retain two separate methods (in my application, the default .getItem and .setItem methods are wrapped).

The results for three browsers and the full code is shown below:

Chrome 29.0:


Firefox 24.0:


IE 10.0:


//This is a test to determine if an additional function should be implemented with web storage for strings and objects separately, or if they can be done in one without significant performance degradation. 
var x = 100000;
var string = "rumpus";

var methods = [
    { type: "string", add: -1, read: -1, length: -1 }, 
    { type: "json", add: -1, read: -1, length: -1 }
var start;

console.log("type\tadd [ms]\tread [ms]\tlength [B]");

for (i = 0; i < methods.length; i++)
    j = x;
    start = new Date().getTime();
    while (j--)
        localStorage.setItem(j, i == 0 ? string : JSON.stringify(string));  
    methods[i].add = new Date().getTime() - start;
    methods[i].length = JSON.stringify(localStorage).length;

    start = new Date().getTime();
    j = x;
    while (j--)
        i == 0 ? localStorage.getItem(j) : JSON.parse(localStorage.getItem(j));
    methods[i].read = new Date().getTime() - start; 
    console.log(methods[i].type + "\t" + methods[i].add + "\t\t" + methods[i].read + "\t\t\t" + methods[i].length);

//log the results
console.log("Analysis for " + x + " iterations");
console.log("size difference per item: " + ((methods[1].length - methods[0].length) / x) + " [Bytes]");
console.log("average add time increase per item: " + ((methods[1].add - methods[0].add) / x) + " [ms]");
console.log("average read time increase per item: " + ((methods[1].read - methods[0].read) / x) + " [ms]");