Last active
May 25, 2023 07:01
-
-
Save jung-kim/83676b2310c7c2a9c3d8 to your computer and use it in GitHub Desktop.
es6 map vs array vs obj performance test
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
"use strict"; | |
let looper = (callback) => { | |
let n = 2000000; | |
while (n > 0) { | |
callback(n); | |
n--; | |
} | |
} | |
let timer = (log, callback) => { | |
let start = Date.now(); | |
callback() | |
console.log(log, Date.now() - start); | |
} | |
let map = new Map(); | |
let obj = {}; | |
let ray = []; | |
timer('Map int key set took: ', () => looper(index => map.set(Math.random() * 2000000, index))); | |
timer('Obj int key set took: ', () => looper(index => obj[Math.random() * 2000000] = index)); | |
timer('ray int key set took: ', () => looper(index => ray[Math.random() * 2000000] = index)); | |
console.log(); | |
timer('Map int key get took: ', () => looper(index => {let dummylet = map.get(Math.random() * 2000000) })); | |
timer('Obj int key get took: ', () => looper(index => {let dummylet = obj[Math.random() * 2000000] })); | |
timer('ray int key get took: ', () => looper(index => {let dummylet = ray[Math.random() * 2000000] })); | |
console.log('\n\n'); | |
map = new Map(); | |
obj = {}; | |
ray = []; | |
timer('Map string key set took: ', () => looper(index => map.set('' + Math.random() * 2000000, '' + index))); | |
timer('Obj string key set took: ', () => looper(index => obj['' + Math.random() * 2000000] = '' + index)); | |
timer('ray string key set took: ', () => looper(index => ray['' + Math.random() * 2000000] = '' + index)); | |
console.log(); | |
timer('Map string key get took: ', () => looper(index => {let dummylet = map.get('' + Math.random() * 2000000) })); | |
timer('Obj string key get took: ', () => looper(index => {let dummylet = obj['' + Math.random() * 2000000] })); | |
timer('ray string key get took: ', () => looper(index => {let dummylet = ray['' + Math.random() * 2000000] })); | |
// // Example output in node v8 | |
// | |
// Map int key set took: 1072 | |
// Obj int key set took: 2460 | |
// ray int key set took: 3457 | |
// | |
// Map int key get took: 824 | |
// Obj int key get took: 1609 | |
// ray int key get took: 2246 | |
// | |
// | |
// | |
// Map string key set took: 1580 | |
// Obj string key set took: 2933 | |
// ray string key set took: 2149 | |
// | |
// Map string key get took: 1511 | |
// Obj string key get took: 1575 | |
// ray string key get took: 1818 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The fact that array is slower than Map makes little sense to me.
Here's a updated benchmark:
Two key points:
updated results