【发布时间】:2013-08-29 14:56:32
【问题描述】:
如何以编程方式在 Google Chrome 中获取我的网站的内存使用情况(JS 和总计)?
我曾考虑使用未记录的 HeapProfiler(参见 here)从 Chrome 扩展程序中执行此操作,但我找不到从中获取数据的方法。
我想在每次发布时测量它的内存消耗,所以这需要编程。
编辑:我想出了如何让 HeapProfiler 方法工作。每个addHeapSnapshotChunk 事件都有一个 JSON 对象块。
chrome.browserAction.onClicked.addListener(function(tab) {
var heapData,
debugId = {tabId:tab.id};
chrome.debugger.attach(debugId, '1.0', function() {
chrome.debugger.sendCommand(debugId, 'Debugger.enable', {}, function() {
function headerListener(source, name, data) {
if(source.tabId == tab.id && name == 'HeapProfiler.addProfileHeader') {
function chunkListener(source, name, data) {
if(name == 'HeapProfiler.addHeapSnapshotChunk') {
heapData += data.chunk;
} else if(name == 'HeapProfiler.finishHeapSnapshot') {
chrome.debugger.onEvent.removeListener(chunkListener);
chrome.debugger.detach(debugId);
//do something with data
console.log('Collected ' + heapData.length + ' bytes of JSON data');
}
}
chrome.debugger.onEvent.addListener(chunkListener);
chrome.debugger.sendCommand(debugId, 'HeapProfiler.getHeapSnapshot', {uid:data.header.uid, type:data.header.typeId});
}
chrome.debugger.onEvent.removeListener(headerListener);
}
chrome.debugger.onEvent.addListener(headerListener);
chrome.debugger.sendCommand(debugId, 'HeapProfiler.takeHeapSnapshot');
});
});
});
解析后,JSON 包含节点、边以及关于节点和边类型和字段的描述性元数据。
或者,如果我只想要总数,我可以使用 Timeline 事件。
也就是说,有没有比我在这里找到的更好的方法?
【问题讨论】:
-
我不确定您需要多少详细信息,但您检查过
window.performance对象吗?它简要概述了内存使用情况,不需要访问扩展。 -
我有,特别是
window.performance.memory。不过,它似乎与堆配置文件不匹配。我实际上不需要很多细节;总内存使用量就足够了。
标签: javascript performance google-chrome google-chrome-devtools memory-profiling