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?
Example of what I am worried:
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