为什么内存消耗增加而不是下降并保持不变

Why is memory consumption increases, than drops and stays constant

我有以下简单程序:

const fs = require("fs");
const time = Date.now();
const file = fs.createWriteStream('./test.txt');

let written = true;

file.on('drain', function () {
    written = true;
});

const interval = setInterval(function () {
    if (Date.now() - time > 10000) {
        clearInterval(interval);
    }

    if (written) {
        written = file.write(new Array(1000000).join('z'));
        console.log(Math.floor(process.memoryUsage().rss / (1024 * 1024)));
    }
}, 100);

并且记录了以下内存消耗:

29 38 48岁 58 67 77 86 96 105 115 125 134 144 153 163 173 182 192 201 211 220 230 240 249 259 268 278 287 297 307 316 326 335 345 355 364 374 383 393 402 412 422 431 441 450 460 470 479 489 498 508 518 527 537 546 556 565 575 585 561

87 97 25 35 44 25 35 44 25 35 44 25 35 44 25 35 44 25 35 44 25 35 44 25 35 44 25 35 44

如您所见,它增长到 561 MB,但下降到 87 MB,然后保持在 100 MB 以下。这里发生了什么?

您的代码正在创建大部分为空的临时对象(new Array(1000000) 只是创建一个 length 设置为 1000000 的空数组;它不会创建包含 1000000 个条目的数组)然后是大的临时对象每 100 毫秒左右读取一次字符串(和一些管家对象)。在某些时候,它会停止这样做(当您将 written 设置为 true 时)。

每次迭代后,数组和管家对象将立即符合垃圾回收条件,一旦完成,字符串将被写入文件。但这并不意味着它们会立即被清理干净。

一旦系统停止这样做,最终垃圾收集就会启动并释放所有这些对象和字符串。

如果计时器继续运行,最终您会看到 GC,即使它是 运行,但您的示例中没有显着的内存压力,因此没有理由优先考虑它。