Last active
August 29, 2015 14:05
-
-
Save mechanicles/5cbdd802d8e49db89236 to your computer and use it in GitHub Desktop.
Ruby's hash sort speed comparison.
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
# 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