Check if two arrays have the same contents (in any order)

前端 未结 9 1749
我在风中等你
我在风中等你 2020-12-24 04:13

I\'m using Ruby 1.8.6 with Rails 1.2.3, and need to determine whether two arrays have the same elements, regardless of whether or not they\'re in the same order. One of the

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-24 04:46

    Speed comparsions

    require 'benchmark/ips'
    require 'set'
    
    a = [1, 2, 3, 4, 5, 6]
    b = [1, 2, 3, 4, 5, 6]
    
    Benchmark.ips do |x|
      x.report('sort')   { a.sort == b.sort }  
      x.report('sort!')  { a.sort! == b.sort! }  
      x.report('to_set') { a.to_set == b.to_set }  
      x.report('minus')  { ((a - b) + (b - a)).empty? }  
    end  
    
    Warming up --------------------------------------
                sort    88.338k i/100ms
               sort!   118.207k i/100ms
              to_set    19.339k i/100ms
               minus    67.971k i/100ms
    Calculating -------------------------------------
                sort      1.062M (± 0.9%) i/s -      5.389M in   5.075109s
               sort!      1.542M (± 1.2%) i/s -      7.802M in   5.061364s
              to_set    200.302k (± 2.1%) i/s -      1.006M in   5.022793s
               minus    783.106k (± 1.5%) i/s -      3.942M in   5.035311s
    

提交回复
热议问题