LRU vs Object

Benchmark created on


Description

Testing a JS LRU vs an Object

Preparation HTML

<script>
function randomStr(len) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",schars="ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var str = '';
	for (var i=0; i<len; i++) {
		if(i==0)
		{
			var rnum = Math.floor(Math.random() * schars.length);
			str += schars.substring(rnum,rnum+1);
		}
		else
		{
			var rnum = Math.floor(Math.random() * chars.length);
			str += chars.substring(rnum,rnum+1);
		}
	}
	return str;
}
class LRU {
    constructor(max = 10) {
        this.max = max;
        this.cache = new Map();
    }

    get(key) {
        let item = this.cache.get(key);
        if (item) {
            // refresh key
            this.cache.delete(key);
            this.cache.set(key, item);
        }
        return item;
    }

    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;
    }
}
</script>

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

Revisions

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