Array Merge (Union)

前端 未结 4 1317
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 18:24

I have two array I need to merge, and using the Union (|) operator is PAINFULLY slow.. are there any other ways to accomplish an array merge?

Also, the arrays are fi

4条回答
  •  甜味超标
    2020-12-13 18:41

    Do you need the items to be in a specific order within the arrays? If not, you may want to check whether using Sets makes it faster.

    Update

    Adding to another answerer's code:

    require "set"
    require "benchmark"
    
    a1 = []; a2 = []
    [a1, a2].each do |a|
      1000000.times { a << rand(999999) }
    end
    
    s1, s2 = Set.new, Set.new
    
    [s1, s2].each do |s|
      1000000.times { s << rand(999999) }
    end
    
    puts "Merge with pipe:"
    puts Benchmark.measure { a1 | a2 }
    
    puts "Merge with concat and uniq:"
    puts Benchmark.measure { (a1 + a2).uniq }
    
    puts "Concat only:"
    puts Benchmark.measure { a1 + a2 }
    
    puts "Uniq only:"
    b = a1 + a2
    puts Benchmark.measure { b.uniq }
    
    puts "Using sets"
    puts Benchmark.measure {s1 + s2}
    
    puts "Starting with arrays, but using sets"
    puts Benchmark.measure {s3, s4 = [a1, a2].map{|a| Set.new(a)} ; (s3 + s4)}
    

    gives (for ruby 1.8.7 (2008-08-11 patchlevel 72) [universal-darwin10.0])

    Merge with pipe:
      1.320000   0.040000   1.360000 (  1.349563)
    Merge with concat and uniq:
      1.480000   0.030000   1.510000 (  1.512295)
    Concat only:
      0.010000   0.000000   0.010000 (  0.019812)
    Uniq only:
      1.460000   0.020000   1.480000 (  1.486857)
    Using sets
      0.310000   0.010000   0.320000 (  0.321982)
    Starting with arrays, but using sets
      2.340000   0.050000   2.390000 (  2.384066)
    

    Suggests that sets may or may not be faster, depending on your circumstances (lots of merges or not many merges).

提交回复
热议问题