gpt4 book ai didi

javascript - 为什么方法 'readdirSync' 在读取包含大量文件的目录时会占用这么多内存?

转载 作者:行者123 更新时间:2023-11-30 00:31:03 25 4
gpt4 key购买 nike

这是一个 NodeJS 代码示例:

var fs = require('fs');

function toMb (byteVal) {
return (byteVal / 1048576).toFixed(2);
}

console.log('Memory usage before "readdirSync" apply: ', toMb(process.memoryUsage()['heapUsed']) + ' MB');

fs.readdirSync('./parseLogFiles/reports');

console.log('Memory usage after "readdirSync" apply: ', toMb(process.memoryUsage()['heapUsed']) + ' MB');

目录“reports”包含 300.000 个文件。

我得到了以下结果:

Memory usage before "readdirSync" apply:  2.01 MB
Memory usage after "readdirSync" apply: 22.38 MB

为什么内存使用增加了 10 倍以上(2.01 对 22.38)?

对于“readdir”我有相同的结果。

另一个例子:

var fs = require('fs');

function toMb (byteVal) {
return (byteVal / 1048576).toFixed(2);
}

console.log('Memory usage before "readdirSync" apply: ', toMb(process.memoryUsage()['heapUsed']) + ' MB');

var filesList = fs.readdirSync('./parseLogFiles/reports');

console.log('Memory usage after "readdirSync" apply: ', toMb(process.memoryUsage()['heapUsed']) + ' MB');
console.log('Files list size: ', toMb(Buffer.byteLength(filesList.join(''))) + ' MB');

我得到了以下结果:

Memory usage before "readdirSync" apply:  2.01 MB
Memory usage after "readdirSync" apply: 22.38 MB
Files list size: 11.13 MB

9,24Mb (22.38 - 11.13 - 2.01) 从哪里来?

最佳答案

这是因为 readdir 的实现方式...

它必须将该目录中的所有 300k 文件加载到内存中才能为您提供列表。 300k 的文件名实际上占用了很多空间 = )

它是在 C scandir 方法之上实现的,该方法进行动态内存分配并根据项目数量递增地增加内存使用量...因此当它读取目录中的项目时,它将不断调整(增加)内存大小需要保存项目列表。

关于javascript - 为什么方法 'readdirSync' 在读取包含大量文件的目录时会占用这么多内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29472146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com