-
-
Save risentveber/2f9fee97f0d4b1b7499e29f6125cb373 to your computer and use it in GitHub Desktop.
This file contains 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 < 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