What is the fastest way to sort a Hash?

后端 未结 3 1822
慢半拍i
慢半拍i 2021-01-21 07:07

People often ask what is the best way to sort a hash, but then they don\'t ask the needed follow-up question about what is the fastest way, which really determ

3条回答
  •  孤街浪徒
    2021-01-21 07:49

    This is a comparison of sort and sort_by when accessing a more complex object:

    require 'fruity'
    
    RUBY_VERSION # => "2.2.2"
    
    class Foo
      attr_reader :key
      def initialize(k)
        @key = k
      end
    
      def <=>(b)
        self.key <=> b.key
      end
    end
    
    HASH = Hash[[*(1..100)].shuffle.map{ |k| [Foo.new(k), 1] }]
    compare do
      _sort1 { HASH.sort.to_h }
      _sort_by { HASH.sort_by{ |k,v| k.key }.to_h }
    end
    # >> Running each test 32 times. Test will take about 1 second.
    # >> _sort_by is faster than _sort1 by 2.7x ± 0.1
    

提交回复
热议问题