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)的?
尝试公开垃圾回收器('node --expose_gc')并在'fs.readdirSync()'之后调用'global.gc()'来查看是否有所作为。 – robertklep 2015-04-06 13:35:19
@robertklep。感谢您的回复。是的,global.gc()清除了内存。 – Carl 2015-04-07 10:26:49