Skip to content

Commit b0026ed

Browse files
author
Viktor Polishchuk
committed
Avoiding recreating logger for the namespace which has been already created. Fix memory leak for a fixed number of categories. For dynamic categories method destroy is still required. #678
1 parent 5c7c61d commit b0026ed

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

src/common.js

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,9 @@ function setup(env) {
1919

2020
/**
2121
* Active `debug` instances.
22+
* @type {Object<String, Function>}
2223
*/
23-
createDebug.instances = [];
24+
createDebug.instances = {};
2425

2526
/**
2627
* The currently active debug mode names, and names to skip.
@@ -62,7 +63,11 @@ function setup(env) {
6263
* @api public
6364
*/
6465
function createDebug(namespace) {
65-
let prevTime;
66+
let prevTime, value = createDebug.instances[namespace];
67+
68+
if (!!value) {
69+
return value;
70+
}
6671

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

7580
// Set `diff` timestamp
7681
const curr = Number(new Date());
77-
const ms = curr - (prevTime || curr);
78-
self.diff = ms;
82+
self.diff = curr - (prevTime || curr);
7983
self.prev = prevTime;
8084
self.curr = curr;
8185
prevTime = curr;
@@ -128,15 +132,14 @@ function setup(env) {
128132
createDebug.init(debug);
129133
}
130134

131-
createDebug.instances.push(debug);
135+
createDebug.instances[namespace] = debug;
132136

133137
return debug;
134138
}
135139

136140
function destroy() {
137-
const index = createDebug.instances.indexOf(this);
138-
if (index !== -1) {
139-
createDebug.instances.splice(index, 1);
141+
if (createDebug.instances.hasOwnProperty(this.namespace)) {
142+
delete createDebug.instances[this.namespace];
140143
return true;
141144
}
142145
return false;
@@ -180,8 +183,10 @@ function setup(env) {
180183
}
181184
}
182185

183-
for (i = 0; i < createDebug.instances.length; i++) {
184-
const instance = createDebug.instances[i];
186+
const keys = Object.keys(createDebug.instances);
187+
188+
for (i = 0; i < keys.length; i++) {
189+
const instance = createDebug.instances[keys[i]];
185190
instance.enabled = createDebug.enabled(instance.namespace);
186191
}
187192
}

0 commit comments

Comments
 (0)