Last active
January 1, 2021 12:50
-
-
Save Tom910/8642ee4d9a4913cd40d1581ab3d95738 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
/* | |
❯ node -v | |
v14.15.1 | |
❯ node Map-vs-native-cache.js | |
Testing caching | |
Map x 57.19 ops/sec ±1.83% (59 runs sampled) | |
Native x 50.16 ops/sec ±2.87% (63 runs sampled) | |
Fastest is Map | |
*/ | |
var Benchmark = require('benchmark'); | |
var suite = new Benchmark.Suite; | |
var testArray = []; | |
for (var s = 0; s < 100000; s++) { | |
testArray.push(Math.random().toString(36).slice(2)); | |
} | |
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 { | |
cache.set(item, item); | |
result.push(item); | |
} | |
} | |
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 { | |
cache[item] = item; | |
result.push(item); | |
} | |
} | |
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