Post

Back to the topic of speed

I'm not very good with writing Ruby map methods - they just haven't quite sunk into my head.  It seems unnatural and awkward for me to think about creating arrays in this way.

And these are the times in my life where I realize I'm staring at a wall that I need to overcome.

So Stackoverflow - being the mecca of all things code-related in my opinion - allows me to post a question:

How would you improve this:

``` lang-rb time =Time.now @time=[]@time.push((time-1.week).strftime("%m-%d"),(time-6.days).strftime("%m-%d"),(time-5.days).strftime("%m-%d"),(time-4.days).strftime("%m-%d"),(time-3.days).strftime("%m-%d"),(time-2.days).strftime("%m-%d"),(time-1.day).strftime("%m-%d"),(time).strftime("%m-%d"))

CODE0 lang-rb time =Time.now iterations =1000Benchmark.bm do|bm| bm.report do iterations.times do@time=7.downto(0).map {|v|(time - v.days).strftime("%m-%d")}endend bm.report do iterations.times do@time=[]@time.push((time-1.week).strftime("%m-%d"),(time-6.days).strftime("%m-%d"),(time-5.days).strftime("%m-%d"),(time-4.days).strftime("%m-%d"),(time-3.days).strftime("%m-%d"),(time-2.days).strftime("%m-%d"),(time-1.day).strftime("%m-%d"),(time).strftime("%m-%d"))endendend

user system total real

0.350000 0.960000 1.310000 (1.310054) 0.310000 0.840000 1.150000 (1.156484)

CODE1 lang-rb @time=(0..7).map {|x|(time - x.days).strftime("%m-%d")}.reverse

CODE2 lang-rb user system total real 0.340000 0.980000 1.320000 (1.321518) 0.300000 0.840000 1.140000 (1.149759)

CODE3 lang-rb user system total real 1.720000 4.800000 6.520000 (6.545335) 1.530000 4.180000 5.710000 (5.712035)

CODE4 lang-rb user system total real

0.040000 0.000000 0.040000 (0.035976) 1.520000 4.180000 5.700000 (5.704401) ```

Holy crap! 5000 iterations and it absolutely destroys my method.

Because he accurately points out that I'm only interested in Dates, I decide to change my own method from Time.now to Date.today and test it:

user system total real

0.090000 0.000000 0.090000 (0.085940) 0.390000 0.000000 0.390000 (0.398143)

It's somewhat weird that in the first test Stefan's method clocks in at 0.0359 and in the second clocks at 0.0859, more than double, but it's still hundredths of a second over 5000 iterations - so I think I'm deep into splitting hairs territory here.

See the original Stackoverflow thread here