我想使用 來測量我的網路 SPA 的記憶體使用情況,performance.memory目的是檢測在 webapp 的生命周期內是否存在任何問題,即記憶體泄漏。
出于這個原因,我需要在特定的時間間隔內呼叫此 API - 它可能是每 3 秒、每 30 秒或每 1 分鐘,......然后我有一個問題 - 快速有效地檢測任何問題我會使間隔盡可能短,但后來我提出了對性能的擔憂。如果測量是一項如此昂貴的任務,測量本身可能會影響 webapp 的性能(但希望我不認為是這種情況)
有了上述背景,我有以下問題:
performance.memory這種方法會影響瀏覽器主執行緒的性能,所以我應該關心使用頻率嗎?是否有正確的方法或程式來確定(Javascript)任務是否影響設備的性能?如果問題 1不確定,那么我將不得不嘗試其他方法來找出呼叫記憶體測量的正確間隔。
uj5u.com熱心網友回復:
(這里是 V8 開發人員。)
通話performance.memory速度相當快。您可以在自己的快速測驗中輕松驗證這一點:只需在回圈中呼叫一千次并測量需要多長時間。
[編輯:感謝@Kaiido 強調這種微基準通常會非常具有誤導性;例如,第一次手術可能要貴得多;或者基準場景可能與實際應用程式的場景如此不同,以至于結果不會延續。請記住,撰寫有用的微基準測驗總是需要對幕后發生的事情有所了解/檢查!
在這種特殊情況下,只要對performance.memory內部作業原理有所了解,這種簡單測驗的結果就大體上是準確的;但是,正如我在下面解釋的那樣,它們也無關緊要。
--編輯結束]
但是,這種觀察不足以解決您的問題。快速的原因performance.memory也是頻繁呼叫它沒有意義的原因:它只是回傳一個快取值,它實際上并沒有做任何作業來衡量記憶體消耗。(如果是這樣,那么呼叫它會非常慢。)這是一個快速測驗來證明這兩點:
function f() {
if (!performance.memory) {
console.error("unsupported browser");
return;
}
let objects = [];
for (let i = 0; i < 100; i ) {
// We'd expect heap usage to increase by ~1MB per iteration.
objects.push(new Array(256000));
let before = performance.now();
let memory = performance.memory.usedJSHeapSize;
let after = performance.now();
console.log(`Took ${after - before} ms, result: ${memory}`);
}
}
f();
(您還可以看到,出于安全原因,瀏覽器會限制計時器粒度:報告的時間為 0 毫秒或 0.1 毫秒并非巧合,絕不會介于兩者之間。)
(第二)然而,這并不像一開始看起來那么嚴重,因為“為了快速有效地檢測任何問題,我必須盡可能縮短間隔”的前提是錯誤的:在垃圾收集語言,記憶體使用量上升和下降是完全正常的,可能達到數百兆位元組。那是因為尋找可以釋放的物件是一項昂貴的作業,因此垃圾收集器經過仔細調整以獲得良好的折衷方案:它們應該盡快釋放記憶體,而不會將 CPU 周期浪費在無用的忙碌作業上。作為這種平衡的一部分,它們會適應給定的作業量,因此這里沒有可參考的一般數字。
Checking memory consumption of your app in the wild is a fine idea, you're not the first to do it, and performance.memory is the best tool for it (for now). Just keep in mind that what you're looking for is a long-term upwards trend, not short-term fluctuations. So measuring every 10 minutes or so is totally sufficient, and you'll still need lots of data points to see statistically-useful results, because any single measurement could have happened right before or right after a garbage collection cycle.
For example, if you determine that all of your users have higher memory consumption after 10 seconds than after 5 seconds, then that's just working as intended, and there's nothing to be done. Whereas if you notice that after 10 minutes, readings are in the 100-300 MB range, and after 20 minutes in the 200-400 MB range, and after an hour they're 500-1000 MB, then it's time to go looking for that leak.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/435988.html
標籤:javascript 表现 谷歌浏览器 v8
