Skip to content

Instantly share code, notes, and snippets.

@sokra
Forked from Tom910/Map-vs-native-cache.js
Last active January 21, 2023 04:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sokra/b36098368da7b8f6792fd7c85fca6311 to your computer and use it in GitHub Desktop.
Save sokra/b36098368da7b8f6792fd7c85fca6311 to your computer and use it in GitHub Desktop.
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
var testArray = [];
for (var s = 0; s < 5000; s++) {
testArray.push(Math.floor(Math.random() * 100));
}
console.log('Testing caching')
suite
.add('Map', () => objectMap(testArray))
.add('MapSingleAccess', () => objectMapSingleAccess(testArray))
.add('Native', () => objectNative(testArray))
.add('NativeSingleAccess', () => objectNativeSingleAccess(testArray))
.on('cycle', event => console.log(String(event.target)))
.on('complete', function() {console.log('Fastest is ' + this.filter('fastest').map('name'))})
.run({ 'async': true });
function objectMap(arr) {
var result = [];
var cache = new Map();
for(var i = 0; i < arr.length; i++) {
var item = arr[i];
if(cache.has(item)) {
result.push(cache.get(item));
} else {
var a = Math.pow(item, 5) * 321312;
cache.set(item, a);
result.push(a);
}
}
return result;
}
function objectMapSingleAccess(arr) {
var result = [];
var cache = new Map();
for(var i = 0; i < arr.length; i++) {
var item = arr[i];
var cacheEntry = cache.get(item);
if(typeof cacheEntry !== "undefined") {
result.push(cacheEntry);
} else {
var a = Math.pow(item, 5) * 321312;
cache.set(item, a);
result.push(a);
}
}
return result;
}
function objectNative(arr) {
var result = [];
var cache = Object.create(null);
for(var i = 0; i < arr.length; i++) {
var item = arr[i];
if(item in cache) {
result.push(cache[item]);
} else {
var a = Math.pow(item, 5) * 321312;
cache[item] = a;
result.push(a);
}
}
return result;
}
function objectNativeSingleAccess(arr) {
var result = [];
var cache = Object.create(null);
for(var i = 0; i < arr.length; i++) {
var item = arr[i];
var cacheEntry = cache[item];
if(typeof cacheEntry !== "undefined") {
result.push(cacheEntry);
} else {
var a = Math.pow(item, 5) * 321312;
cache[item] = a;
result.push(a);
}
}
return result;
}
@aminya
Copy link

aminya commented Jan 1, 2021

This benchmark does not show the whole story. Your key is just a number. Map is designed for strings keys.

Here is the better benchmark
https://jsbench.me/h1kje2tt1b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment