I would add my ¢2. If you are likely to make an operation a few times on huge arrays, @sawa’s method is definitely your choice:
require 'benchmark'
n = 1_000
a1 = 1_000.times.map { rand(1..100) }
a2 = 1_000.times.map { rand(5..95) }
Benchmark.bm do |x|
x.report {
n.times do
a1 - (a1 - a2)
end
}
x.report {
n.times do
a1.keep_if { |xx| a2.include? xx }
end
}
end
results in:
# user system total real
# 0.340000 0.000000 0.340000 ( 0.424604)
# 5.590000 0.010000 5.600000 ( 6.438095)
But if there are lots of subtractions on small arrays:
- n = 1_000
- a1 = 1_000.times.map { rand(1..100) }
- a2 = 1_000.times.map { rand(5..95) }
+ n = 100_000
+ a1 = 10.times.map { rand(1..100) }
+ a2 = 10.times.map { rand(5..95) }
the opposite looks more appropriate:
# user system total real
# 0.550000 0.010000 0.560000 ( 0.551997)
# 0.150000 0.000000 0.150000 ( 0.151695)