Kri*_*ave 8 javascript memory-leaks
我目前正在忙着写一个javascript库.在那个库中,我想提供一些关于控制台内容的日志.
function log () {
if ((window && typeof (window.console) === "undefined") || !enableLogging) {
return false;
}
function currentTime() {
var time = new Date();
return time.getHours() + ':' + time.getMinutes() + ':' + time.getSeconds() + '.' + time.getMilliseconds();
}
var args = [];
args.push(currentTime());
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
switch (arguments[0]) {
case severity.exception:
if (window.console.exception) {
window.console.exception.apply(console, args);
} else {
window.console.error.apply(console, args);
}
break;
case severity.error:
window.console.error.apply(console, args);
break;
case severity.warning:
window.console.warning.apply(console, args);
break;
case severity.information:
window.console.log.apply(console, args);
break;
default:
window.console.log.apply(console, args);
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码显示了我的日志功能.调用时,我至少提供一个sevirity,一条消息和一些可选的对象(可以是IDBTransaction,IDBDatabase等的DOM对象).
log(severity.information, 'DB opened', db);
Run Code Online (Sandbox Code Playgroud)
现在我遇到的问题是这会导致内存泄漏.问题是我传递的对象通过console.log方法保留在内存中.有没有办法避免这种情况或清理它?
Dmi*_*ich 16
传递给的对象console.log
不是GC的,这是可以理解的,因为你需要能够在代码运行后在开发人员工具中检查它们.我根本不会将此称为问题,因为在调试应用程序时需要这样做,但生产代码不应该执行任何控制台日志记录.
如果您仍需要在生产中记录内容(或将其发送到某处),我建议您对对象进行字符串化:
console.log(JSON.stringify(db, null, '\t')); // '\t' to pretty print
Run Code Online (Sandbox Code Playgroud)
这里的额外的奖金是你真正捕捉对象的状态下记录的时间(在登录对象引用不 保证 该 1).
由于您尝试记录大型对象,请注意这样做可能会降低性能,因此如果要在生产中执行此操作,请三思而后行.
归档时间: |
|
查看次数: |
5425 次 |
最近记录: |