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
Before I answer the question you asked, I’m going to answer the question you should have asked but didn’t:
A: Make your code readable and correct first, then, and only if there is a performance problem, start to worry about performance by measuring where the performance problem is first and only then making changes to your code.
Now to answer the question you asked, but shouldn’t have:
method1.rb:
method2.rb:
Results of brain-dead benchmark:
Looks to me like user time usage (the important factor) has method1.rb a lot faster. You, of course, should not trust this benchmark and should make your own reflecting your actual code use. This, however, is something you should do only after you have determined which code is your performance bottleneck in reality. (Hint: 99.44% of computer programmers are 100% wrong when they guess where their bottlenecks are without measuring!)