Skip to content

Instantly share code, notes, and snippets.

@tamouse
Last active December 19, 2015 13:29
Show Gist options
  • Save tamouse/5962804 to your computer and use it in GitHub Desktop.
Save tamouse/5962804 to your computer and use it in GitHub Desktop.
Hash key and value sort, with reverse, comparing sort and sort_by implementations
$ ruby HashSort.rb
user system total real
ksort 0.160000 0.000000 0.160000 ( 0.154819)
ksortb 0.090000 0.000000 0.090000 ( 0.091088)
vsort 0.150000 0.000000 0.150000 ( 0.147454)
vsortb 0.080000 0.000000 0.080000 ( 0.088772)
reverse_ksort 0.160000 0.000000 0.160000 ( 0.157565)
reverse_ksortb 0.090000 0.000000 0.090000 ( 0.089768)
reverse_vsort 0.150000 0.010000 0.160000 ( 0.151634)
reverse_vsortb 0.090000 0.000000 0.090000 ( 0.092445)
class Hash
def ksort
Hash[self.sort{|a,b| a.first <=> b.first}]
end
def vsort
Hash[self.sort{|a,b| a.last <=> b.last}]
end
def ksortb
Hash[self.sort_by{|x| x.first}]
end
def vsortb
Hash[self.sort_by{|x| x.last}]
end
def reverse_ksort
Hash[self.sort{|a,b| a.first <=> b.first}.reverse]
end
def reverse_vsort
Hash[self.sort{|a,b| a.last <=> b.last}]
end
def reverse_ksortb
Hash[self.sort_by{|x| x.first}.reverse]
end
def reverse_vsortb
Hash[self.sort_by{|x| x.last}.reverse]
end
end
require 'benchmark'
tries = 1_000
h={}
1.upto(100) {|i| h[rand(10_000)] = rand(1_000_000) }
Benchmark.bm(25) do |x|
x.report("ksort") { tries.times {h.ksort} }
x.report("ksortb") { tries.times {h.ksortb} }
x.report("vsort") { tries.times {h.vsort} }
x.report("vsortb") { tries.times {h.vsortb} }
x.report("reverse_ksort") { tries.times {h.reverse_ksort} }
x.report("reverse_ksortb") { tries.times {h.reverse_ksortb} }
x.report("reverse_vsort") { tries.times {h.reverse_vsort} }
x.report("reverse_vsortb") { tries.times {h.reverse_vsortb} }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment