Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `map` faster than `each`?

Tags:

ruby

Is map faster at iterating over the array than each? Is there speed difference between the two?

  • Map

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

    result = []
    arr.each do |a| 
      result.push(a + 2)
    end
    
like image 620
Deekor Avatar asked Jul 21 '15 01:07

Deekor


People also ask

Which is faster for each or map?

map() is faster than forEach() Show activity on this post.

Are maps faster?

map may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.

What is the difference between each and map in rails?

So each is used for processing an array and map is used to do something with a processed array.


1 Answers

I think yes.

I've tried this test

require "benchmark"

n=10000
arr=Array.new(10000,1)
Benchmark.bm do |x|
  #Map
  x.report do
    n.times do
      result = arr.map {|a| a + 2}
    end
  end


  #Each
  x.report do
    n.times do
      result = []
      arr.each do |a|
        result.push(a + 2)
      end
    end
  end
end

And I got this times

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

Seems like map it's faster

I saw this video http://confreaks.tv/videos/goruco2015-how-to-performance she shows many ruby profiles and tools, if you are interested to improve your performance you will find a lot of tips there.

added

This is a crazy behavior for me!

require "benchmark"

n=10000
arr=Array.new(10000,1)
Benchmark.bm do |x|
  #Map
  x.report do
    n.times do
      result = arr.map {|a| a + 2}
    end
  end
  #Each and push
  x.report do
    n.times do
      result = []
      arr.each do |a|
        result.push(a + 2)
      end
    end
  end

 #Each and <<
  x.report do
    n.times do
      result = []
      arr.each do |a|
        result << (a + 2)
      end
    end
  end
end

and the 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 the operator "<<" faster than method push? I didn't expect that, I thought that was a kind of alias.

like image 90
Horacio Avatar answered Oct 11 '22 05:10

Horacio