Alexandre Morgaut, writing at Quora:

localStorage (as sessionStorage) is synchronous in the sense that it is a virtually blocking API. When an instruction saving data in localStorage is executed, the next instruction in the script will only be executed once the data is (somehow) saved.

Since localStorage is synchronous, maintaining optimal performance to its read and write is really important, especially if localStorage has an important role within your application. About a month ago,1 I was interested in finding out whether it made sense to consolidate all of a site’s localStorage objects into a single master object that was then read once and kept in a JavaScript variable for the lifetime of the page. I tested this idea by creating a bunch of small objects, saving them to localStorage, reading them all back, and then comparing this to doing the exact same process with fewer, larger objects. The numbers I went with were one thousand 100-byte items and ten 10,000-byte items. Here’s what the code looked like for this:

let test = (numBlocks, byteSze) => {
  let bytes = '';
  for (let i = 0; i < byteSze; i++) {
    bytes += 'a';
  }
  for (let i = 0; i < numBlocks; i++) {
    localStorage.setItem(`test${i}`, bytes);
  }
  for (let i = 0; i < numBlocks; i++) {
    localStorage.getItem(`test${i}`);
  }
}
test(1000, 100);
localStorage.clear();
test(10, 10000);
localStorage.clear();

To keep the result skewing minimal, I found that it was helpful to run the first data set and then reload the browser before running the second data set. I used Chrome’s profiling tool to get the exact timeframe of how long each of these took. Since both took mere milliseconds and other processes got CPU clock time, I ran each test a few times to get an accurate idea of their duration under a normal load. It took approximately ten milliseconds to run the first test and one millisecond to run the second test.

The conclusion is simple. If you have the choice of storing ten items in localStorage separately versus in an aggregated object, the latter is a better idea from a performance standpoint. You’d probably intuitively guess that to be the case, but it’s good to have cold numbers as confirmation.

Here’s a gist that outlines my findings, complete with screenshots.


  1. The reason I’m just now getting around to writing about this is because while it was exciting researching this, publishing my findings has proven to be much harder than moving on to the next shiny thing. ↩︎