Skip to content

Instantly share code, notes, and snippets.

@risentveber
Forked from Tom910/Map-vs-native-cache.js
Created February 27, 2017 13:33
Show Gist options
  • Save risentveber/2f9fee97f0d4b1b7499e29f6125cb373 to your computer and use it in GitHub Desktop.
Save risentveber/2f9fee97f0d4b1b7499e29f6125cb373 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 < 100000; s++) {
testArray.push(Math.floor(Math.random() * 100));
}
console.log('Testing caching')
suite
.add('Map', () => objectMap(testArray))
.add('Native', () => objectNative(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 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment