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
map() is faster than forEach() Show activity on this post.
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.
So each is used for processing an array and map is used to do something with a processed array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With