In memory cache

JavaScript performance comparison

Test case created by numtel

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  // Randomly generate this many cached items per type
  const CACHE_SIZE = 1000;
  
  const Expired = Symbol();
  
  function validateCacheHit(itemPair, cacheTtl) {
    if(itemPair) {
      if(typeof cacheTtl === 'number'
          && (Date.now() - itemPair[1] ) / 1000 > cacheTtl) return Expired;
      return itemPair[0];
    }
    return itemPair;
  }
  
  class MapCache extends Map {
    set(key, value) {
      return super.set(key, [value, Date.now()]);
    }
    get(key, cacheTtl) {
      return validateCacheHit(super.get(key), cacheTtl);
    }
  }
  
  class ObjCache {
    constructor() {
      this.data = {};
    }
    set(key, value) {
      this.data[key] = [value, Date.now()];
    }
    get(key, cacheTtl) {
      return validateCacheHit(this.data[key], cacheTtl);
    }
  }
  
  const myMapCache = new MapCache;
  const myObjCache = new ObjCache;
  
  function randomCacheItem() {
    const out = [];
    const outLen = Math.random() * 15000;
    for(let i = 0; i < outLen; i++) out.push(Math.random());
    return out;
  }
  
  // Populate caches
  const fetchOrder = [];
  for(let i = 0; i < CACHE_SIZE; i++) {
    const item = randomCacheItem();
    const key = String(i);
    myMapCache.set(key, item);
    myObjCache.set(key, item);
  }
  

};
</script>

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
Map backed cache
const key = String(Math.floor(Math.random() * CACHE_SIZE));
myMapCache.get(key, 60);
pending…
Obj backed cache
const key = String(Math.floor(Math.random() * CACHE_SIZE));
myObjCache.get(key, 60);
pending…

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

Compare results of other browsers

0 Comments