Hi,
Which of these two forms of Array Initialization is better in Ruby?
Method 1:
DAYS_IN_A_WEEK = (0..6).to_a
HOURS_IN_A_DAY = (0..23).to_a
@data = Array.new(DAYS_IN_A_WEEK.size).map!{ Array.new(HOURS_IN_A_DAY.size) }
DAYS_IN_A_WEEK.each do |day|
HOURS_IN_A_DAY.each do |hour|
@data[day][hour] = 'something'
end
end
Method 2:
DAYS_IN_A_WEEK = (0..6).to_a
HOURS_IN_A_DAY = (0..23).to_a
@data = {}
DAYS_IN_A_WEEK.each do |day|
HOURS_IN_A_DAY.each do |hour|
@data[day] ||= {}
@data[day][hour] = 'something'
end
end
The difference between the first method and the second method is that the second one does not allocate memory initially. I feel the second one is a bit inferior when it comes to performance due to the numerous amount of Array copies that has to happen.
However, it is not straight forward in Ruby to find what is happening. So, if someone can explain me which is better, it would be really great!
Thanks