Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
require 'benchmark'
require 'rubygems'
require 'json'
require 'yaml'
include Benchmark
benchmark_iterations = 1
large_single_dimension_array = [42, 123.123] * 5000
large_single_dimension_hash = {}
10000.times do |i|
large_single_dimension_hash["key#{i}".intern] = i
end
class Fixnum
alias to_ruby to_s
end
class Float
alias to_ruby to_s
end
class String
alias to_ruby inspect
end
class Symbol
def to_ruby
":#{to_s}"
end
end
class Array
def to_ruby
"[#{map {|x| x.to_ruby}.join(',')}]"
end
end
class Hash
def to_ruby
"{#{map {|k, v| "#{k.to_ruby} => #{v.to_ruby}"}.join(", ")}}"
end
end
benchmark do |t|
t.report("array marshal") do
benchmark_iterations.times {
Marshal.load(Marshal.dump(large_single_dimension_array))
}
end
t.report("array json") do
benchmark_iterations.times {
JSON.load(JSON.dump(large_single_dimension_array))
}
end
t.report("array eval") do
benchmark_iterations.times {
eval(large_single_dimension_array.to_ruby)
}
end
t.report("array yaml") do
benchmark_iterations.times {
YAML.load(YAML.dump(large_single_dimension_array))
}
end
t.report("hash marshal") do
benchmark_iterations.times {
Marshal.load(Marshal.dump(large_single_dimension_hash))
}
end
t.report("hash json") do
benchmark_iterations.times {
JSON.load(JSON.dump(large_single_dimension_hash))
}
end
t.report("hash eval") do
benchmark_iterations.times {
eval(large_single_dimension_hash.to_ruby)
}
end
t.report("hash yaml") do
benchmark_iterations.times {
YAML.load(YAML.dump(large_single_dimension_hash))
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment