Skip to content

Instantly share code, notes, and snippets.

@luislavena
Last active August 29, 2015 14:18
Show Gist options
  • Save luislavena/be4e7fa9cc980bc28844 to your computer and use it in GitHub Desktop.
Save luislavena/be4e7fa9cc980bc28844 to your computer and use it in GitHub Desktop.
require "benchmark/ips"
require "granola"
require "json"
require "msgpack"
require "multi_json"
require "oj"
require "yajl"
User = Struct.new(:name, :age)
class UserSerializer < Granola::Serializer
MIME_TYPES[:msgpack] = "application/x-msgpack".freeze
def data
{ name: object.name, age: object.age }
end
def to_msgpack(*)
MessagePack.pack(data)
end
end
SERIALIZER = UserSerializer.new(User.new("John Doe", 30))
Benchmark.ips do |b|
b.report("yajl") do
Granola.json = ->(data, _) { Yajl::Encoder.encode(data) }
10_1000.times { SERIALIZER.to_json }
end
b.report("json") do
Granola.json = ->(data, _) { JSON.dump(data) }
10_1000.times { SERIALIZER.to_json }
end
b.report("oj") do
Granola.json = ->(data, _) { Oj.dump(data, mode: :compat) }
10_1000.times { SERIALIZER.to_json }
end
b.report("msgpack") do
10_1000.times { SERIALIZER.to_msgpack }
end
b.report("multi_json/yajl") do
MultiJson.use :yajl
Granola.json = MultiJson.method(:encode)
10_1000.times { SERIALIZER.to_json }
end
b.report("multi_json/json") do
MultiJson.use :json_gem
Granola.json = MultiJson.method(:encode)
10_1000.times { SERIALIZER.to_json }
end
b.report("multi_json/oj") do
MultiJson.use :oj
Granola.json = MultiJson.method(:encode)
10_1000.times { SERIALIZER.to_json }
end
b.compare!
end
$ ruby -v
ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-darwin14]
$ bundle show
Gems included by the bundle:
* benchmark-ips (2.1.1)
* bundler (1.9.2)
* granola (0.10.1)
* json (1.8.2)
* msgpack (0.5.11)
* multi_json (1.11.0)
* oj (2.12.1)
* yajl-ruby (1.2.1)
Calculating -------------------------------------
yajl 1.000 i/100ms
json 1.000 i/100ms
oj 1.000 i/100ms
msgpack 1.000 i/100ms
multi_json/yajl 1.000 i/100ms
multi_json/json 1.000 i/100ms
multi_json/oj 1.000 i/100ms
-------------------------------------------------
yajl 1.731 (± 0.0%) i/s - 9.000
json 1.329 (± 0.0%) i/s - 7.000 in 5.268963s
oj 3.250 (± 0.0%) i/s - 17.000
msgpack 4.989 (± 0.0%) i/s - 25.000
multi_json/yajl 1.011 (± 0.0%) i/s - 6.000 in 5.932494s
multi_json/json 1.023 (± 0.0%) i/s - 6.000 in 5.865207s
multi_json/oj 1.409 (± 0.0%) i/s - 8.000 in 5.677987s
Comparison:
msgpack: 5.0 i/s
oj: 3.2 i/s - 1.54x slower
yajl: 1.7 i/s - 2.88x slower
multi_json/oj: 1.4 i/s - 3.54x slower
json: 1.3 i/s - 3.75x slower
multi_json/json: 1.0 i/s - 4.88x slower
multi_json/yajl: 1.0 i/s - 4.93x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment