I have a large array (10+ million objects) that I want to combine into a single object (for simplicity, let's assume here a string) and run each element in the array through some processing (abstracted by the function do_stuff
). There are two natural ways to do this:
memo = ""
big_array.each do |e|
memo << do_stuff(e)
end
memo
and
big_array.reduce("") do |memo, e|
memo + do_stuff(e)
end
The reduce/inject syntax is more aesthetically appealing, but the question is which is more memory efficient. We already know that each is marginally more time efficient than reduce, but what about memory?
I'm also not clear on how I could profile memory usage in Ruby, especially over just a block of code, so if someone can provide some pointers to that I would also appreciate it.