Ruby PStore vs Marshal表演

时间:2016-03-18 12:57:51

标签: ruby marshalling

我正在尝试决定是否在代码中实现PStore而不是将各种对象保存为Marshal。 以下代码尝试比较两种方法的性能:

require 'pstore'

def m_dump(filename, object)
    File.open(filename,"wb") do |f|
        Marshal.dump(object, f)
    end
end

def m_load(filename)
    object = nil
    File.open(filename,'rb') do |f|
        object = Marshal.load(f)
    end
    return object
end

test = {}
test[:pi] = [Math::PI]*100000000

start = Time.now
m_dump("test.marshal", test);nil
puts "Marshal File written in #{(Time.now - start).to_s}"

start = Time.now
results = PStore.new("test.pstore")
results.transaction{results[:test] = test};nil
puts "Pstore File written in #{(Time.now - start).to_s}"

start = Time.now
test2 = m_load("test.marshal");nil
puts "Marshal File read in #{(Time.now - start).to_s}"

start = Time.now
results2 = PStore.new("test.pstore")
test3 = results2.transaction{results2[:test]};nil
puts "Pstore read in #{(Time.now - start).to_s}"

puts "Marshal check #{test2 == test}"
puts "Pstore check #{test3 == test}"

运行代码会产生以下结果:

Marshal File written in 7.936485
Pstore File written in 5.526494
Marshal File read in 5.890848
Pstore read in 11.135965

创建新存档时PStore似乎稍微快一点,但是必须读取数据时要慢得多。

鉴于PStore基于Marshal,我预计会有类似的表现。这种行为是期待的吗?

1 个答案:

答案 0 :(得分:0)

transaction => transaction(true) 其中“ true”表示只读。然后,性能将与marshall相似。

start = Time.now
results2 = PStore.new("test.pstore")
test3 = results2.transaction(true) {results2[:test]}; nil
puts "Pstore read in #{(Time.now - start).to_s}"