From: "Jesús Gabriel y Galán" Date: 2010-08-31T01:40:40+09:00 Subject: Re: A small problem for arrays On Mon, Aug 30, 2010 at 5:45 PM, Ruby Users Ruby Users wrote: > Robert Klemme wrote: >> On 21.08.2010 18:27, Jean-Julien Fleck wrote: >>> =>  [5, 6, 7] >>>       Array Difference---Returns a new array that is a copy of the >>>       original array, removing any items that also appear in other_array. >>>       (If you need set-like behavior, see the library class Set.) >>> >>>          [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]  #=>   [ 3, 3, 5 ] >>> >>> Cheers, >>> >> >> Just adding to that: if Arrays are large and / or there are frequent set >> operations needed then using class Set might yield better performance. >> >> Kind regards >> >>   robert > > -- Just adding to that: if Arrays are large and / or there are frequent > set > -- operations needed then using class Set might yield better > performance. > I do't much understand what you mean. If not hard can give you an > example... It means that there are some operations that are more efficient in Set than in Array, and that if you need a lot of those, it would be better to use Set instead. For example, the intersection of two Sets is faster than the intersection of two Arrays: require 'benchmark' require 'set' n = 1_000 a1 = (1..10_000).map {|x| rand(100)} a2 = (1..10_000).map {|x| rand(100)} s1 = Set.new.merge a1 s2 = Set.new.merge a2 Benchmark.bmbm do |x| x.report("array minus") do n.times {a1 - a2} end x.report("set &") do n.times {s1 & s2} end end $ ruby set_bm.rb Rehearsal ----------------------------------------------- array minus 0.900000 0.000000 0.900000 ( 0.935476) set & 0.280000 0.070000 0.350000 ( 0.361684) -------------------------------------- total: 1.250000sec user system total real array minus 0.880000 0.010000 0.890000 ( 0.890552) set & 0.280000 0.070000 0.350000 ( 0.353687) Jesus.