localStorage vs. Objects

JavaScript performance comparison

Test case created by Nicholas C. Zakas

Preparation code

  localStorage.setItem("foo", "body { background: blue; margin: 10px; padding: 10px; color: black; text-decoration: none; }");
  var FOO = {
   foo: "body { background: blue; margin: 10px; padding: 10px; color: black; text-decoration: none; }"
  var value;

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Reading from localStorage
value = localStorage.getItem("foo");
Reading from an object
value = FOO.foo;

Compare results of other browsers


You can edit these tests or add even more tests to this page by appending /edit to the URL.


Jason Persampieri commented :

Considering the dominance of iOS devices, I wonder how this does on desktops with SSDs. Do browsers not have a localStorage in-memory cache?

Alexander commented :

So, access to local storage should be treated the same way as access to .property values that are referenced repeatedly – create a locally scoped var, store the value in the var, and only reference the var repeatedly.

I edited the tests to test that theory, but then realized, I have no idea what the scope of the code snippets is… http://jsperf.com/localstorage-vs-objects/3

Mark Kawakami commented :

Chrome's numbers are bizarre! Their object reads are by far the fastest of any browser, but their localStorage numbers are the slowest by an even greater (much greater margin). They're about 40x slower than an iPhone!

Jonathan Kemp commented :

Isn't this obvious? I'm pretty sure that localStorage requires spinning up the hard drive. Reading from an object in memory should be way faster. The tests showed that.

Matt commented :

When reading from localStorage you're using a function, whereas when reading from an object you use direct property access. I wonder if the results were slightly different, if you called a function like that:

var FOO = {
  "foo" : 42,
  "get" : function (prop) {
    return this[prop];

value = FOO.get("foo");

Frederic commented :

SSDs don't have any impact:

Chrome 11.0.696.57 on Mac OS X 10.6.7 (MacBook Air)
Reading from an object

Reading from localStorage

David commented :

Same here. SSDs don't have any impact:

Firefox 4.0.1 on Linux x86_64 Reading from an object 66,371,629

Reading from localStorage 45,321

Mathias Bynens commented :

You’re comparing FOO.foo to localStorage.getItem('foo') here. For a fair test you should probably skip the function call, and use localStorage.foo (which works just as well in this case).

Update: Someone made a revision with these changes: http://jsperf.com/localstorage-vs-objects/10