LRU vs Object (v2)

Revision 2 of this benchmark created on


Description

Testing a JS LRU vs an Object

Setup

class LRU {
    constructor(max = 10) {
        this.max = max;
        this.cache = new Map();
    }

    get(key) {
        return this.cache.get(key);
    }
    
    has(key) {
        return this.cache.has(key);
    }
    
    set(key, val) {
        // refresh key
        if (this.cache.has(key)) this.cache.delete(key);
        // evict oldest
        else if (this.cache.size == this.max) this.cache.delete(this.first());
        this.cache.set(key, val);
    }

    first() {
        return this.cache.keys().next().value;
    }
}
class SetLRU {
    constructor(max = 10) {
        this.max = max;
        this.cache = new Set();
    }
    
    has(key) {
        return this.cache.has(key);
    }
    
    add(key) {
        // refresh key
        if (this.cache.has(key)) this.cache.delete(key);
        // evict oldest
        else if (this.cache.size == this.max) this.cache.delete(this.first());
        this.cache.add(key);
    }

    first() {
        return this.cache.values().next().value;
    }
}

Test runner

Ready to run.

Testing in
TestOps/sec
Object
let OBJ = {};
for(let i = 0; i < 1000000; i++) {
    let key = i.toString();
    OBJ[i] = true;
    if(i >= 10) {
        for(let x in OBJ) {
            delete OBJ[x];
            break;
        }
    }
}
ready
LRU
let myLRU = new LRU();
for(let i = 0; i < 1000000; i++) {
    let key = i.toString();
    myLRU.set(key, true);
}
ready
Set LRU
let mySetLRU = new SetLRU();
for(let i = 0; i < 1000000; i++) {
    let key = i.toString();
    mySetLRU.add(key);
}
ready

Revisions

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