What is the fastest way to sort a Hash?

后端 未结 3 1823
慢半拍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 08:08

    Here are some more interesting things to consider:

    require 'fruity'
    
    puts "Running Ruby v#{ RUBY_VERSION }"
    # >> Running Ruby v2.2.2
    
    require 'fruity'
    
    puts "Running Ruby v#{ RUBY_VERSION }"
    # >> Running Ruby v2.2.2
    

    This looks at the differences using an integer as a key:

    HASH = Hash[[*(1..100)].shuffle.map{ |k| [k, 1] }]
    compare do
      _sort1 { HASH.sort.to_h }
      _sort2 { HASH.sort{ |a, b| a[0] <=> b[0] }.to_h }
      _sort3 { HASH.sort{ |a, b| a.first <=> b.first }.to_h }
      _sort_by { HASH.sort_by{ |k,v| k }.to_h }
    end
    # >> Running each test 64 times. Test will take about 1 second.
    # >> _sort_by is faster than _sort2 by 70.0% ± 1.0%
    # >> _sort2 is faster than _sort3 by 19.999999999999996% ± 1.0%
    # >> _sort3 is faster than _sort1 by 19.999999999999996% ± 1.0%
    

    This looks at the differences using a single-character string as the key:

    HASH = Hash[[*('a'..'Z')].shuffle.map{ |k| [k, 1] }]
    compare do
      _sort1 { HASH.sort.to_h }
      _sort2 { HASH.sort{ |a, b| a[0] <=> b[0] }.to_h }
      _sort3 { HASH.sort{ |a, b| a.first <=> b.first }.to_h }
      _sort_by { HASH.sort_by{ |k,v| k }.to_h }
    end
    # >> Running each test 16384 times. Test will take about 1 second.
    # >> _sort1 is similar to _sort3
    # >> _sort3 is similar to _sort2
    # >> _sort2 is faster than _sort_by by 1.9x ± 0.1
    

提交回复
热议问题