LRU vs Object (v8)

Revision 8 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) {
    	if(key in this.cache) {
    		let val = this.cache[key];
    		delete this.cache[key];
    		this.cache[key] = val;
    		return val;
    	}
    	return null;
    }
    
    has(key) {
        let res = key in this.cache;
        if(res) {
        	let val = this.cache[key];
       		delete this.cache[key];
    		this.cache[key] = val;
        }
        return res;
    }
    
    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) {
        if(this.cache.has(key)) {
    		let val = this.cache.get(key);
    		this.cache.delete(key);
    		this.cache.set(key, val);
    		return val;
    	}
    	return null;
    }
    
    has(key) {
        let res = key in this.cache;
        if(res) {
    		let val = this.cache.get(key);
    		this.cache.delete(key);
    		this.cache.set(key, val);
        }
        return res;
    }
    
    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) {
    	let res = this.cache.has(key);
    	if(res) {
    		this.cache.delete(key);
    		this.cache.add(key);
    	}
    	return res;
    }
    
    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.