Memory leak when registering complex objects

I'm currently busy writing a javascript library. In this library I want to provide some information about what is happening with the console.

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; } 

The above code presents the log function. When called, I provide at least a sequence, a message, and optionally some objects (can be DOM objects such as IDBTransaction, IDBDatabase, ...).

 log(severity.information, 'DB opened', db); 

Now the problem is that this leads to a memory leak. The problem is that the objects I pass remain in memory using the console.log method. Is there any way to avoid this or clear it?

+8
javascript memory-leaks
source share
1 answer

It is clear that the objects passed to console.log are not GC'ed, because you should be able to check them in the developer tools after running your code. I would not call this a problem at all, because it should be so when you are debugging your application, but production code should not keep console logging.

If you still need to record material (or send it somewhere) to production, I would suggest scribbling your object:

 console.log(JSON.stringify(db, null, '\t')); // '\t' to pretty print 

An additional bonus here is that you really record the state of the object during logging (when registering a link to an object which is 1 ).

Since you are trying to register large objects, keep in mind that this will probably decrease performance, so think twice if you want to do this in production.

1 - seems to be fixed in latest Chrome

+13
source share

All Articles