我看到以下代码存在内存泄漏:
while (true) {
console.log("Testing.");
}
我尝试过定义字符串并使用常量,但是它仍会泄漏内存。
var test = "Testing.";
while (true) {
console.log(test);
}
如果我使用文件而不是标准日志,就会发生相同的泄漏:
var test = "Testing.";
var fh = fs.createWriteStream("test.out", {flags: "a"});
while (true) {
fh.write(test);
}
我原以为是因为我没有正确关闭文件,但我尝试了这个方法,仍然发现有内存泄漏:
var test = "Testing";
while (true) {
var fh = fs.createWriteStream("test.out", {flags: "a"});
fh.end(test);
fh.destroy();
fh = null;
}
有没有人能给我一些提示,告诉我如何在不泄漏内存的情况下编写代码?
fs.createWriteStream
)复现您的解决方案,但如果我尝试使用console.log
,我仍然会遇到内存泄漏问题。function writeConsole() { console.log("test"); if (typeof(gc) == "function") gc(); process.nextTick(writeConsole); } writeConsole();
当我使用node test.js
运行上述代码块时,我发现每次迭代都会使我的内存使用量增加。当我将其作为node --expose-gc test.js
运行时,我没有看到任何持续增加的情况。 - facetious