簡単なHashの深いコピーぐらいならMarshal使わないほうがいいかもという話(実行時間的に)。
ベンチマーク取りました。
rubyのバージョン 2.1.2p95
marshal_bench.rb
require 'benchmark'
puts Benchmark::CAPTION
source_hash = {
'key1' => ['first', 'second', 'third'],
'key2' => ['one', 'two'],
'key3' => ['single']
}
duped = Marshal.load(Marshal.dump(source_hash))
marshal_block = ->{ Marshal.load(Marshal.dump(source_hash)) }
assign_block = ->{
new_hash = {}
source_hash.each do |k, v|
value = []
v.each do |e|
value.push(e)
end
new_hash[k] = value
end
new_hash
}
puts Benchmark.measure {
10000.times do |i|
marshal_block.call
end
}
puts Benchmark.measure {
10000.times do |i|
assign_block.call
end
}
new_hash = assign_block.call
source_hash.each do |k, v|
p (v.__id__ != new_hash[k].__id__)
end
結果(オブジェクトIDがことなることの確認も含む)
user system total real
0.180000 0.000000 0.180000 ( 0.182431)
0.020000 0.000000 0.020000 ( 0.023417)
true
true
true