The Eclectic Quill

Website of Joshua McGee

By

Getting the current year in Ruby on Rails

In Ruby on Rails, there are a number of ways to get the current year, but they are not all created equal.

The two methods recommended most frequently are Date.current.year and Time.new.year.  So I profiled these with the following code in Rails 3 that runs each routine a million times:

puts Benchmark.realtime { (10**6).times { Time.new.year } }
puts Benchmark.realtime { (10**6).times { Date.current.year } }

Time.new.year takes 5.479458 seconds to finish the million operations on my computer.  Date.current.year takes 12.323462 seconds -- more than twice as long.

I shared this with a colleague, who found the article Ruby Date Class Slows You Down? Rewrite It In C!, detailing the reasons and the author's suggested workarounds.

Leave a Reply

Your email address will not be published. Required fields are marked *