2015-04-06 124 views
2

下面是代码的NodeJS为例:为什么readdirSync方法在使用大量文件读取目录时会占用大量内存?

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'); 

目录 “报告” 包含300.000文件。

我已经得到了以下结果:

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

为什么内存使用增加了超过10倍(2.01 VS 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)的?

+0

尝试公开垃圾回收器('node --expose_gc')并在'fs.readdirSync()'之后调用'global.gc()'来查看是否有所作为。 – robertklep 2015-04-06 13:35:19

+0

@robertklep。感谢您的回复。是的,global.gc()清除了内存。 – Carl 2015-04-07 10:26:49

回答

1

这是因为READDIR的执行方式...

它在该目录中的所有文件300K加载到内存给你的列表中。 300k文件名实际占用大量空间=)

它在C scandir方法的基础上实现,该方法执行动态内存分配,并基于项目数增量增加内存使用量......以便读取项目在目录中,它将不断调整(增加)保存项目列表所需的内存。