Created
April 26, 2017 16:23
-
-
Save seawolf/c280b46d1dece4fe621badc01ce154d9 to your computer and use it in GitHub Desktop.
Hash Serialisation in Ruby between Marshal, JSON and YAML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
my_hash = { symbol_key: 'string value', 'string key' => :symbol_value, 123 => 456, nil => true } | |
def do_this #&blk | |
last_result = nil | |
(1..10_000).map { |i| last_result = yield(i) } | |
last_result | |
end | |
def factor(this, compared_to_this, precision=2) | |
(this / compared_to_this).round(precision) | |
end | |
require "benchmark" | |
Benchmark.bm(7) do |x| | |
result = nil | |
marshal_run = x.report("Marshal:") { result = do_this { Marshal.load( Marshal.dump(my_hash) ) } }.total | |
puts result.inspect | |
json_run = x.report("JSON:") { result = do_this { JSON.parse( JSON.dump(my_hash) ) } }.total | |
puts result.inspect | |
yaml_run = x.report("YAML:") { result = do_this { YAML.load( YAML.dump(my_hash) ) } }.total | |
puts result.inspect | |
puts "Compared to Marshal, JSON is #{factor(json_run, marshal_run)} slower and YAML is #{factor(yaml_run, marshal_run)} slower." | |
end | |
----- | |
user system total real | |
Marshal: 0.060000 0.010000 0.070000 ( 0.054295) | |
{:symbol_key=>"string value", "string key"=>:symbol_value, 123=>456, nil=>true} | |
JSON: 0.160000 0.010000 0.170000 ( 0.175384) | |
{"symbol_key"=>"string value", "string key"=>"symbol_value", "123"=>456, ""=>true} | |
YAML: 2.690000 0.120000 2.810000 ( 2.806745) | |
{:symbol_key=>"string value", "string key"=>:symbol_value, 123=>456, nil=>true} | |
Compared to Marshal, JSON is 2.43 slower and YAML is 40.14 slower. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment