The Eclectic Quill

Website of Joshua McGee


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  So I profiled these with the following code in Rails 3 that runs each routine a million times:

puts Benchmark.realtime { (10**6).times { } }
puts Benchmark.realtime { (10**6).times { Date.current.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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.