Skip to content

Instantly share code, notes, and snippets.

@QQism
Forked from aishfenton/serializer_benchmarks.rb
Last active January 6, 2020 01:01
Show Gist options
  • Save QQism/00b8734904f7ec60cafcd6b737670da1 to your computer and use it in GitHub Desktop.
Save QQism/00b8734904f7ec60cafcd6b737670da1 to your computer and use it in GitHub Desktop.
Performance comparison of different ruby serializer methods
# gem install bson
# gem install bson_ext
# gem install yajl-ruby
# gem install json
# gem install msgpack
# gem install oj
require 'rubygems'
require 'benchmark'
require 'yaml'
require 'bson'
require 'json'
require 'yajl'
require 'msgpack'
require 'oj'
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 = msg.to_bson.to_s
when :msgpack
str = MessagePack.pack(msg)
when :oj
str = Oj.dump(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 = Hash.from_bson(BSON::ByteBuffer.new(str))
when :msgpack
msg = MessagePack.unpack(str)
when :oj
msg = Oj.load(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
r.report("Oj") do
SAMPLES.times do
msg = decode(encode(obj, :oj), :oj)
end
end
end
# Results
# -------
# user system total real
# Marshal 0.027234 0.000000 0.027234 ( 0.027210)
# JSON (built-in ruby 2.6.5) 0.044245 0.000000 0.044245 ( 0.044307)
# JSON (using Yajl) 0.031962 0.000000 0.031962 ( 0.031960)
# BSON 0.026627 0.000000 0.026627 ( 0.026615)
# YAML 0.795025 0.009725 0.804750 ( 0.804792)
# MessagePack 0.017875 0.000000 0.017875 ( 0.017878)
# Oj 0.015515 0.000000 0.015515 ( 0.015516)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment