Story
During some tests for a performance critical code, I observed a side-effect of Math.random() that I do not understand. I am looking for
- some deep technical explanation
- a falsification for my test (or expectation)
- link to a V8 problem/bug ticket
Problem
It looks like that calling Math.random()
allocates some memory that needs to be cleaned up by the Gargabe Collector (gc).
Test: With Math.random()
const numberOfWrites = 100;
const obj = {
value: 0
};
let i = 0;
function test() {
for(i = 0; i < numberOfWrites; i++) {
obj.value = Math.random();
}
}
window.addEventListener('DOMContentLoaded', () => {
setInterval(() => {
test();
}, 10);
});
Observation 1: Chrome profile
Chrome: 95.0.463869, Windows 10, Edge: 95.0.1020.40
Running this code in the browser and record a perfromance profile will result in a classic memory zig-zag
Memory profile of Math.random() test
Obersation 2: Firefox
Firefox Developer: 95, Windows 10
No Garbage Collection (CC/GCMinor) detected - memory quite linear
Workarounds
crypto.getRandomValues()
Replace Math.random()
with a large enough array of pre-calculated random numbers using self.crypto.getRandomValues`.
Aucun commentaire:
Enregistrer un commentaire