-
-
Save sokra/b36098368da7b8f6792fd7c85fca6311 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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