Array include any value from another array?

后端 未结 5 1980
青春惊慌失措
青春惊慌失措 2020-12-12 12:23

What\'s the most efficient way to test if an array contains any element from a second array?

Two examples below, attempting to answer the question does foods

5条回答
  •  我在风中等你
    2020-12-12 13:05

    require "benchmark"
    N = 1_000_000
    puts "ruby version: #{RUBY_VERSION}"
    
    CHEESES = %w(chedder stilton brie mozzarella feta haloumi).freeze
    FOODS = %w(pizza feta foods bread biscuits yoghurt bacon).freeze
    
    Benchmark.bm(15) do |b|
      b.report("&, empty?") { N.times { (FOODS & CHEESES).empty? } }  
      b.report("any?, include?") { N.times { FOODS.any? {|food| CHEESES.include?(food) } } }  
      b.report("disjoint?") { N.times { FOODS.to_set.disjoint? CHEESES.to_set }}
    end  
                          user     system      total        real
    &, empty?         0.751068   0.000571   0.751639 (  0.752745)
    any?, include?    0.408251   0.000133   0.408384 (  0.408438)
    disjoint?        11.616006   0.014806  11.630812 ( 11.637300)
    

提交回复
热议问题