Skip to content

Instantly share code, notes, and snippets.

@mechanicles
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mechanicles/5cbdd802d8e49db89236 to your computer and use it in GitHub Desktop.
Save mechanicles/5cbdd802d8e49db89236 to your computer and use it in GitHub Desktop.
Ruby's hash sort speed comparison.
# using ruby-2.1.1
require "benchmark"
n = 100_000
hash = { "for" => "sale",
"to_price" => "1000000",
"bath" => "0;6",
"bed" => "0;6",
"from_price" => "150000",
"price" => "150000;1000000",
"bed" => "0;6" }
Benchmark.bm do |x|
x.report('Using hash.keys.sort method:') do
n.times do
new_hash = {}
hash.keys.sort.each do |key|
new_hash[key] = hash[key]
end
end
end
x.report('Using hash.sort.to_h method:') do
n.times do
new_hash = {}
new_hash = hash.sort.to_h
end
end
end
# =>
# user system total real
# Using hash.keys.sort method: 0.280000 0.000000 0.280000 ( 0.279664)
# Using hash.sort.to_h method: 0.490000 0.000000 0.490000 ( 0.492064)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment