jsPerf.app is an online JavaScript performance benchmark test runner & jsperf.com mirror. It is a complete rewrite in homage to the once excellent jsperf.com now with hopefully a more modern & maintainable codebase.
jsperf.com URLs are mirrored at the same path, e.g:
https://jsperf.com/negative-modulo/2
Can be accessed at:
https://jsperf.app/negative-modulo/2
Testing a JS LRU vs an Object
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;
}
}
Ready to run.
Test | Ops/sec | |
---|---|---|
Object |
| ready |
LRU |
| ready |
Set LRU |
| ready |
You can edit these tests or add more tests to this page by appending /edit to the URL.