From: gabriele renzi Date: 2004-04-21T17:14:06+09:00 Subject: Re: efficient collect+compact ? il 21 Apr 2004 01:27:07 GMT, Martin Pirker ha scritto:: >Hello... > >What's the most efficient way for > >puts [1,2,3,4,5,6,7,8,9,10].collect{ |x| next if x % 2 == 0; x+10 }.compact >or >puts [1,2,3,4,5,6,7,8,9,10].collect!{ |x| next if x % 2 == 0; x+10 }.compact! > try yourself: map!+compact! 11 0.141000 0.000000 0.141000 ( 0.141000) map+compact 21 0.078000 0.000000 0.078000 ( 0.078000) inject 21 0.235000 0.000000 0.235000 ( 0.234000) external 21 0.093000 0.000000 0.093000 ( 0.094000) external for 21 0.094000 0.000000 0.094000 ( 0.094000) # code require 'benchmark' Z=(1..100000).to_a Benchmark.bm(10) do |b| b.report 'map!+compact! ' do ary=Z.map!{ |x| next if x % 2 == 0; x+10 }.compact! p ary[0] end b.report 'map+compact ' do ary=Z.map{ |x| next if x % 2 == 0; x+10 }.compact p ary[0] end b.report 'inject ' do ary=Z.inject([]) { |s, x| x % 2 == 0 ? s : s << x + 10 } p ary[0] end b.report 'external ' do ary=[] Z.each {|x| ary<<(x+10) unless x%2==0 } p ary[0] end b.report 'external for ' do ary=[] for i in Z ary<<(i+10) unless i%2==0 end p ary[0] end end