大型对象上的JSON.parse()使用的内存比它应该的多 [英] JSON.parse() on a large array of objects is using way more memory than it should
问题描述
我生成一个~200'000元素的对象数组(在 map
中使用对象文字符号而不是 new Constructor()
),我将 JSON.stringify
'd版本保存到磁盘,占用31 MB,包括换行符和一个空格 - per-indentation level( JSON.stringify(arr,null,1)
)。
I generate a ~200'000-element array of objects (using object literal notation inside map
rather than new Constructor()
), and I'm saving a JSON.stringify
'd version of it to disk, where it takes up 31 MB, including newlines and one-space-per-indentation level (JSON.stringify(arr, null, 1)
).
然后,在一个新的节点进程,我将整个文件读入UTF-8字符串并将其传递给 JSON.parse
:
Then, in a new node process, I read the entire file into a UTF-8 string and pass it to JSON.parse
:
var fs = require('fs');
var arr1 = JSON.parse(fs.readFileSync('JMdict-all.json', {encoding : 'utf8'}));
根据Mavericks的活动监视器,节点内存使用量约为1.05 GB!即使在我的古老4 GB RAM机器上输入终端也感觉比较懒。
Node memory usage is about 1.05 GB according to Mavericks' Activity Monitor! Even typing into a Terminal feels laggier on my ancient 4 GB RAM machine.
但是,如果在新的节点进程中,我将文件的内容加载到字符串中,请将其切断在元素边界处, JSON.parse
单独的每个元素,表面上得到相同的对象数组:
But if, in a new node process, I load the file's contents into a string, chop it up at element boundaries, and JSON.parse
each element individually, ostensibly getting the same object array:
var fs = require('fs');
var arr2 = fs.readFileSync('JMdict-all.json', {encoding : 'utf8'}).trim().slice(1,-3).split('\n },').map(function(s) {return JSON.parse(s+'}');});
节点仅使用~200 MB的内存,并且没有明显的系统延迟。这种模式在节点的多次重启中持续存在: JSON.parse
整个数组需要一大堆内存,而在元素方面解析它会更加节省内存。
node is using just ~200 MB of memory, and no noticeable system lag. This pattern persists across many restarts of node: JSON.parse
ing the whole array takes a gig of memory while parsing it element-wise is much more memory-efficient.
这篇关于大型对象上的JSON.parse()使用的内存比它应该的多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!