(Array # each + Array # push) v.s. Array # map

The beginning of things

I often see this code in reviews.

hoge_array = []
fuga_array.each do |val|
  hohe_array << something(val)
end

It is generally well known that this is a slow code, and it is known that it is about 1.6 times slower. (Source here) By the way, not many people explain why it's slow. Honestly

hoge_array = fuga_array.map do |val|
  something(val)
end

It's easier to read, and that's fine, but this time I'll review the reason for actively using map.

Thing you want to do

--Difference between ʻArray # map and ʻArray # each + ʻArray # push (or ʻArray # <<)

Processing comparison

Array#<<

Processing order

Recommended Posts

(Array # each + Array # push) v.s. Array # map
Array / list / map
[Each, map ...] I compared the array processing tonight [ruby]