51

ruby – 为什么重复的JSON解析消耗越来越多的内存?

 5 years ago
source link: https://codeday.me/bug/20190112/504867.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

似乎在Ruby中一遍又一遍地解析相同的JSON文件会占用越来越多的内存.

考虑下面的代码和输出:

>为什么在第一次迭代后没有释放内存?

>解析后,为什么116MB JSON文件会占用1.5Gb的RAM?考虑到文本文件被转换为哈希值,这是令人惊讶的.我在这里想念的是什么?

码:

require 'json'

def memused
  `ps ax -o pid,rss | grep -E "^[[:space:]]*#{$$}"`.strip.split.map(&:to_i)[1]/1024
end

text = IO.read('../data-grouped/2012-posts.json')
puts "before parsing: #{memused}MB"
iter = 1
while true
  items = JSON.parse(text)
  GC.start
  puts "#{iter}: #{memused}MB"
  iter += 1
end

输出:

before parsing: 116MB
1: 1840MB
2: 2995MB
3: 2341MB
4: 3017MB
5: 2539MB
6: 3019MB

当Ruby解析JSON文件时,它会创建许多中间对象来实现目标. GC开始工作之前,这些对象会保留在内存中.

如果JSON文件具有复杂的结构,许多数组和内部对象,那么数字也会快速增长.

您是否尝试调用“GC.start”来建议Ruby清理未使用的内存?如果内存量

显着减少,它建议只是用于解析数据的中间对象,否则,您的数据结构很复杂,或者您的数据存在lib无法解除分配的内容.

对于大型JSON处理,我使用yajl-ruby( https://github.com/brianmario/yajl-ruby ).它是C实现的,占用空间小.

翻译自:https://stackoverflow.com/questions/17153194/why-does-repeated-json-parsing-consume-more-and-more-memory


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK