Sort hash by key, return hash in Ruby

前端 未结 10 1449
时光取名叫无心
时光取名叫无心 2020-11-27 10:05

Would this be the best way to sort a hash and return Hash object (instead of Array):

h = {\"a\"=>1, \"c\"=>3, \"b\"=>2, \"d\"=>4}
# => {\"a\"=         


        
10条回答
  •  被撕碎了的回忆
    2020-11-27 10:37

    No, it is not (Ruby 1.9.x)

    require 'benchmark'
    
    h = {"a"=>1, "c"=>3, "b"=>2, "d"=>4}
    many = 100_000
    
    Benchmark.bm do |b|
      GC.start
    
      b.report("hash sort") do
        many.times do
          Hash[h.sort]
        end
      end
    
      GC.start
    
      b.report("keys sort") do
        many.times do
          nh = {}
          h.keys.sort.each do |k|
            nh[k] = h[k]
          end
        end
      end
    end
    
           user     system      total        real
    hash sort  0.400000   0.000000   0.400000 (  0.405588)
    keys sort  0.250000   0.010000   0.260000 (  0.260303)
    

    For big hashes difference will grow up to 10x and more

提交回复
热议问题