localStorage + JSON and caching

Benchmark created by Gilmore on


Preparation HTML

<script>
  var obj = {obj:{with:["various",123],properties:true}}
  localStorage["storedObj"] = JSON.stringify(obj);
  
  var dataCache = (function() {
    var cache = {}
  
    return {
      get: function(key) {
        var cached = cache[key]
        if (!cached) {
          cached = cache[key] = JSON.parse(localStorage[key])
        }
        return cached
      },
      clear: function () {
        cache = {}
      }
    }
  })()
  
  var getDataDirect = function(key) {
    return JSON.parse(localStorage[key])
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Direct once
dataCache.clear()
getDataDirect("storedObj")
ready
Cached once
dataCache.clear()
dataCache.get("storedObj")
ready
Direct multiple
dataCache.clear()
getDataDirect("storedObj")
getDataDirect("storedObj")
getDataDirect("storedObj")
ready
Cached multiple
dataCache.clear()
dataCache.get("storedObj")
dataCache.get("storedObj")
dataCache.get("storedObj")
ready

Revisions

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

  • Revision 1: published by Gilmore on