我对这里的性能很好奇,所以我测试了一些变化。这是一个更好地优化性能的解决方案(在我的基准测试中比公认的解决方案快大约 8 倍)。通过一次增加一个月,我们可以删除uniq
节省大量时间的调用。
start_date = 1.year.ago.to_date
end_date = Date.today
dates = []
date = start_date.beginning_of_month
while date <= end_date.beginning_of_month
dates << date.to_date.to_s
date += 1.month
end
dates
#=> ["2019-02-01", "2019-03-01", "2019-04-01", "2019-05-01", "2019-06-01", "2019-07-01", "2019-08-01", "2019-09-01", "2019-10-01", "2019-11-01", "2019-12-01", "2020-01-01", "2020-02-01"]
基准测试结果:
Comparison:
month increment loop: 17788.3 i/s
accepted solution: 2140.1 i/s - 8.31x slower
基准代码的要点