ruby - Is `map` faster than `each`? -


is map faster @ iterating on array each? there speed difference between two?

  • map

    result = arr.map {|a| + 2} 
  • each

    result = [] arr.each |a|    result.push(a + 2) end 

i think yes.

i've tried test

require "benchmark"  n=10000 arr=array.new(10000,1) benchmark.bm |x|   #map   x.report     n.times       result = arr.map {|a| + 2}     end   end     #each   x.report     n.times       result = []       arr.each |a|         result.push(a + 2)       end     end   end end 

and got times

       user     system      total        real    5.790000   0.060000   5.850000 (  5.846956)    8.210000   0.030000   8.240000 (  8.233849) 

seems map it's faster

i saw video http://confreaks.tv/videos/goruco2015-how-to-performance shows many ruby profiles , tools, if interested improve performance find lot of tips there.

added

this crazy behavior me!

require "benchmark"  n=10000 arr=array.new(10000,1) benchmark.bm |x|   #map   x.report     n.times       result = arr.map {|a| + 2}     end   end   #each , push   x.report     n.times       result = []       arr.each |a|         result.push(a + 2)       end     end   end   #each , <<   x.report     n.times       result = []       arr.each |a|         result << (a + 2)       end     end   end end 

and result

       user     system      total        real    5.880000   0.080000   5.960000 (  5.949504)    8.160000   0.010000   8.170000 (  8.164736)    6.630000   0.010000   6.640000 (  6.632686) 

is operator "<<" faster method push? didn't expect that, thought kind of alias.


Comments