【问题标题】:Composing json from cached strings in ruby从 ruby​​ 中的缓存字符串组合 json
【发布时间】:2013-03-07 19:34:01
【问题描述】:

考虑以下场景,我需要将很多大哈希放入一个数组中,然后将其转换为 json:

hash1 = { ... big hash ... }
hash2 = { ... big hash ... }
hash3 = { ... big hash ... }
array = [hash1, hash2, hash3]

json = JSON.dump(array)

问题是从这些哈希生成 json 需要很长时间,所以我想缓存它。但是,我不能缓存整个数组,只能缓存单独的项目。显然将缓存的 json 字符串放入数组中会产生不好的结果:

hash1 = {:a => 1}
hash1json = JSON.dump(hash1)
array = [hash1json]
JSON.generate(array)
==> ["{\"a\":1}"]

当我需要的时候

==> [{"a":1}]

我能想到的唯一方法是做这样的事情:

"[#{[hash1json].join(",")}]"
==> [{"a":1}]

这对于这种特定情况可能已经足够了,但是如果想要缓存一些深层结构而不是简单的数组,那就更难了。

【问题讨论】:

  • 我用 JSON.dump 检查了我之前的答案,但它没有用 - 抱歉!

标签: ruby json yajl


【解决方案1】:

事实证明这实际上非常简单:

class CachedJson
  def initialize(str)
    @str = str
  end

  def to_json
    @str
  end
end

puts Yajl::Encoder.encode(:data => [{:a => 1}, '{"b":2}'])
# => {"data":[{"a":1},"{\"b\":2}"]}

puts Yajl::Encoder.encode(:data => [{:a => 1}, CachedJson.new('{"b":2}')])
# => {"data":[{"a":1},{"b":2}]}

在后台 yajl 对每个对象调用 to_json,并且此方法必须返回字符串,因此只需使用 CachedJson 对象包装缓存的 json 字符串即可

【讨论】:

    【解决方案2】:

    编辑

    我之前的回答完全错过了问题的性能方面(对此感到抱歉),所以这是我的发现。或许对你有一点帮助。

    显然在这些情况下使用yajl-ruby,它是C yajl 库的绑定,似乎在进行转换时提高了性能。例如,这里我正在生成一个带有 10,000 条目的哈希:

      require 'json'
      require 'yajl'
      require 'benchmark'
      tmp = "" 
      10000.times do |i|
       tmp += "\"#{i}\" => \"#{i}\", " 
      end
    
     domains = eval("{#{tmp}}")
    
     puts "JSON DUMP #{Benchmark.measure { JSON.dump(domains) }} "
    
     puts "Yajl::Encoder #{Benchmark.measure { Yajl::Encoder.encode(domains)}}"
    

    结果如下:

    JSON DUMP   0.010000   0.000000   0.010000 (  0.007495)
    
    Yajl::Encoder   0.000000   0.000000   0.000000 (  0.003542)
    

    我始终将转换为 json 的任务的时间减半。希望对您有所帮助!

    【讨论】:

    • 解析缓存的 json 字符串只是为了再次将其转换为 json 有什么意义?我这里说的是性能优化。
    • @teamon 抱歉,我更新了我的答案。希望对您有所帮助。
    • 感谢您的努力,但不,它根本没有帮助。我已经在使用 yajl(我已经为 ruby​​ 测试了所有可用的 json 库),唯一让事情变得更快的方法是将哈希缓存为呈现的 json。我已经在缓存哈希,但这还不够。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 2015-12-13
    • 2011-05-14
    相关资源
    最近更新 更多