Skip to content

Commit

Permalink
Avoiding recreating logger for the namespace which has been already c…
Browse files Browse the repository at this point in the history
…reated. Fix memory leak for a fixed number of categories. For dynamic categories method destroy is still required. debug-js#678
  • Loading branch information
Viktor Polishchuk committed Apr 22, 2019
1 parent 5c7c61d commit b0026ed
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions src/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@ function setup(env) {

/**
* Active `debug` instances.
* @type {Object<String, Function>}
*/
createDebug.instances = [];
createDebug.instances = {};

/**
* The currently active debug mode names, and names to skip.
Expand Down Expand Up @@ -62,7 +63,11 @@ function setup(env) {
* @api public
*/
function createDebug(namespace) {
let prevTime;
let prevTime, value = createDebug.instances[namespace];

if (!!value) {
return value;
}

function debug(...args) {
// Disabled?
Expand All @@ -74,8 +79,7 @@ function setup(env) {

// Set `diff` timestamp
const curr = Number(new Date());
const ms = curr - (prevTime || curr);
self.diff = ms;
self.diff = curr - (prevTime || curr);
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
Expand Down Expand Up @@ -128,15 +132,14 @@ function setup(env) {
createDebug.init(debug);
}

createDebug.instances.push(debug);
createDebug.instances[namespace] = debug;

return debug;
}

function destroy() {
const index = createDebug.instances.indexOf(this);
if (index !== -1) {
createDebug.instances.splice(index, 1);
if (createDebug.instances.hasOwnProperty(this.namespace)) {
delete createDebug.instances[this.namespace];
return true;
}
return false;
Expand Down Expand Up @@ -180,8 +183,10 @@ function setup(env) {
}
}

for (i = 0; i < createDebug.instances.length; i++) {
const instance = createDebug.instances[i];
const keys = Object.keys(createDebug.instances);

for (i = 0; i < keys.length; i++) {
const instance = createDebug.instances[keys[i]];
instance.enabled = createDebug.enabled(instance.namespace);
}
}
Expand Down

0 comments on commit b0026ed

Please sign in to comment.