LRU vs Object (v3)

Revision 3 of this benchmark created on


Description

Testing a JS LRU vs an Object

Setup

class ObjectLRU {
	constructor(max = 10) {
        this.max = max;
        this.cache = {};
        this.size = 0;
    }

    get(key) {
        return this.cache[key];
    }
    
    has(key) {
        return key in this.cache;
    }
    
    set(key, val) {
        // refresh key
        if (key in this.cache) {
        	delete this.cache[key];
        } else if (this.size == this.max) {
        	for(let x in this.cache) {
        		delete this.cache[x];
        		break;
        	}
        } else {
        	this.size++;
        }
        this.cache[key] = val;
    }
}
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 myObjLRU = new ObjectLRU();
for(let i = 0; i < 1000000; i++) {
    let key = i.toString();
    myObjLRU.set(key, true);
}
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.