I wonder how to measure total memory used by the function in JavaScript. I found that there is an API performance.memory. I have noticed that usedJSHeapSize is not only for the single page but can also share summary between other tabs. Let's assume that in my case, I have always opened only one tab, so I should measure memory of only this one tab I am interested in. I also read that I should wait some time after function execution to let garbage collector clear all unused memory. In the end, I came up with below a solution, but I do not know is it a good idea and is the way how I measure memory correct. If you have any thoughts about that, let me know please.
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function fun1() {
// function logic...
}
function fun2() {
// function logic...
}
function measureMemory(functionToMeasure) {
const memoryStart = performance.memory.usedJSHeapSize;
functionToMeasure();
const memoryEnd = performance.memory.usedJSHeapSize;
return memoryEnd - memoryStart;
}
async function runBenchmark() {
const totalMemoryUsedByFun1 = measureMemory(fun1);
// I wait 2min to be sure garbage collector clean all unused memory
await wait(120000);
const totalMemoryUsedByFun2 = measureMemory(fun2);
}
What do you think, is it a good approach/idea of measuring memory used by function? Does 2min is enough time for garbage-collector to clear unused memory?
function fun1() {
// alocates 1000KB
}
function fun2() {
// alocates 300KB
}
// initial heap size = 0
const memoryUsedByFun1 = measureMemory(fun1());
// Heap size is equal 1000KB
// Now let's say I do not wait for GC and only 500KB have been released
// heap size before measuring fun2 is equal to 500KB
const memoryUsedByFun2 = measureMemory(fun2());
// While fun2 is running, 500KB of fun1 allocations have been released
// So now if I do memoryStart - memoryEnd
// Where memory start was 500KB and memory end is equal to 300KB
// because 500KB was released while computing fun2
// I will get result 500KB - 300KB = 200KB
// What is not true because fun2 allocates 300KB)
I also have seen that there is such API
measureUserAgentSpecificMemory(), but I think this API is not working at all even after turning on#experimental-web-platform-features
Why are you waiting for garbage collector?
You're already diffing memoryEnd - memoryStart so even if you still have residual memory assigned on the heap when it starts, you will see the difference by the end.
Are you worried that gc will clean up residual memory WHILE the second function is executing?.
Usually gc runs exactly after a function was called. If you have circular refferences it will use the mark and sweep algorithm to garbage collect later since it isn't able to determine with the refference count algorithm if the object is still used (but I'm assuming it waits for the stack to be free to run it). —- LE: Actually it doesn’t wait so your concern is valid.
Here's a nice article I found about garbage collector in js