Skip to content

Instantly share code, notes, and snippets.

@ssut
Created Apr 15, 2014
Embed
What would you like to do?
Ruby Object Serialization Performance Test (Native vs OJ Library)
require 'benchmark'
require 'oj'
require 'json'
require 'ostruct'
N_OJ = 500_000
ex_HASH = { 'one' => 1, 'array' => [ true, false ] }
ex_JSON = '{ "one": 1, "array": [ true, false ] }'
ex_STRUCT = OpenStruct.new( one: 1, hash: ex_HASH, array: [ true, false ] )
ex_MARSHAL = "\x04\bU:\x0FOpenStruct{\b:\bonei\x06:\thash{\aI\"\bone\x06:\x06ETi\x06I\"\narray\x06;\bT[\aTF:\narray[\aTF"
ex_OJ = "{\"^o\":\"OpenStruct\",\"table\":{\":one\":1,\":hash\":{\"one\":1,\"array\":[true,false]},\":array\":[true,false]}}"
Benchmark.bm(20) do |x|
x.report('native json dump') do
N_OJ.times do
y = JSON.dump(ex_HASH)
end
end
x.report('oj json dump') do
N_OJ.times do
y = Oj.dump(ex_HASH)
end
end
x.report('native json load') do
N_OJ.times do
y = JSON.load(ex_JSON)
end
end
x.report('oj json load') do
N_OJ.times do
y = Oj.load(ex_JSON)
end
end
x.report('native marshal dump') do
N_OJ.times do
y = Marshal.dump(ex_STRUCT)
end
end
x.report('oj object dump') do
N_OJ.times do
y = Oj.dump(ex_STRUCT)
end
end
x.report('native marshal load') do
N_OJ.times do
y = Marshal.load(ex_MARSHAL)
end
end
x.report('oj object load') do
N_OJ.times do
y = Oj.load(ex_OJ)
end
end
end
user system total real
native json dump 2.410000 0.010000 2.420000 ( 2.410244)
oj json dump 0.290000 0.000000 0.290000 ( 0.290253)
native json load 3.400000 0.020000 3.420000 ( 3.444769)
oj json load 0.750000 0.000000 0.750000 ( 0.746503)
native marshal dump 3.680000 0.000000 3.680000 ( 3.688319)
oj object dump 0.660000 0.000000 0.660000 ( 0.665804)
native marshal load 9.190000 0.020000 9.210000 ( 9.202852)
oj object load 1.870000 0.000000 1.870000 ( 1.877643)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment