Last active
December 9, 2022 08:43
-
-
Save jung-kim/d146b25ea754e73bf60a to your computer and use it in GitHub Desktop.
Map vs WeakMap performance
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
"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 weakMap = new WeakMap(); | |
let keys = []; | |
for (var m = 0; m < 2000000; m++) { | |
keys.push({}); | |
} | |
timer('Map set took: ', () => looper(index => map.set(keys[Math.floor(Math.random() * 2000000)], index))); | |
timer('weakMap set took: ', () => looper(index => weakMap.set(keys[Math.floor(Math.random() * 2000000)], index))); | |
console.log(); | |
timer('Map int key get took: ', () => looper(index => {let dummylet = map.get(keys[Math.floor(Math.random() * 2000000)]) })); | |
timer('weakMap int key get took: ', () => looper(index => {let dummylet = weakMap.get(keys[Math.floor(Math.random() * 2000000)]) })); | |
// # node v8 sample output | |
// | |
// Map set took: 1781 | |
// weakMap set took: 1278 | |
// | |
// Map int key get took: 723 | |
// weakMap int key get took: 681 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sorry, but this test is awful :D
Math.floor(Math.random() * 2000000)
inside the test callback. Which is 90% of the recorded execution time for e.g.map.get()
. What you want is to test just the native JS functions nothing else.Math.random()
makes it impossible to compare e.g.map.set()
vs.weakMap.set()
.Date.now()
isms
based, if the loop finishes in less than 1ms or even if you want more precision you get a problem.console.log()
blocks CPU resources because of the async re-render of the output while execution of next test continues.This works better:
performance.now()
for subms
percisionPerformanceObserver()
and logging at the endSidenote:
Your implementation tests 2Mio iterations (~4s on my browser). With pre-calculated key/values. This test tests 20Mio iterations in ~ 2s on my browser.