# sudo gem install bson # sudo gem install bson_ext # sudo gem install yajl-ruby # sudo gem install json # sudo gem install msgpack require 'rubygems' require 'benchmark' require 'yaml' require 'bson' require 'json' require 'yajl' require 'msgpack' def encode(msg, format) case format when :yaml str = msg.to_yaml when :binary str = Marshal.dump(msg) when :json str = JSON.generate(msg) when :yajl str = Yajl::Encoder.encode(msg) when :bson str = BSON.serialize(msg).to_s when :msgpack str = MessagePack.pack(msg) end str end def decode(str, format) msg = nil case format when :yaml msg = YAML.load(str) when :binary msg = Marshal.load(str) when :json msg = JSON.parse(str) when :yajl msg = Yajl::Parser.parse(str) when :bson msg = BSON.deserialize(str) when :msgpack msg = MessagePack.unpack(str) end msg end SAMPLES = 5_000 obj = { :name => "Fredrick Smith", :quantity => 1_000_000, :addresses => { :address1 => "12 Heather Street, Parnell, Auckland, New Zealand", :address2 => "1 Queen Street, CBD, Auckland, New Zealand" } } Benchmark.bmbm do |r| r.report("Marshal") do SAMPLES.times do decode(encode(obj, :binary), :binary) end end r.report("JSON (built-in ruby 1.9.2)") do SAMPLES.times do decode(encode(obj, :json), :json) end end r.report("JSON (using Yajl)") do SAMPLES.times do decode(encode(obj, :yajl), :yajl) end end r.report("BSON") do SAMPLES.times do decode(encode(obj, :bson), :bson) end end r.report("YAML") do SAMPLES.times do decode(encode(obj, :yaml), :yaml) end end r.report("MessagePack") do SAMPLES.times do msg = decode(encode(obj, :msgpack), :msgpack) end end end # Results # ------- # user system total real # Marshal 0.090000 0.000000 0.090000 ( 0.097608) # JSON (built-in ruby 1.9.2) 0.250000 0.000000 0.250000 ( 0.261509) # JSON (using Yajl) 0.110000 0.020000 0.130000 ( 0.121666) # BSON 0.260000 0.000000 0.260000 ( 0.263860) # YAML 1.160000 0.020000 1.180000 ( 1.174353) # MessagePack 0.030000 0.000000 0.030000 ( 0.030526)