November 16, 2010
When Rails 1.1 introduced <>> in 2006, many people, including me, embraced the convenience and elegance of being able to write code such as this:<>>
instead of the equivalent standard Ruby syntax:<>>
Others pointed out that the <>> approach was much slower than using an explicit block. A commenter on this post on Josh Susser's blog, for example, shows a benchmark revealing <>> to be 3.4 times slower on one example.
In the intervening years, <>> has become part of standard distribution of Ruby 1.8.7 and Ruby 1.9. Being curious about its performance on current Ruby implementations, I constructed a simple benchmark and ran it on the Rubies that I have installed under RVM. My version of the benchmark measures performance of <>> when used with <>> on arrays of a variety of lengths.
The benchmark code and raw result data can be found here. The table below summarizes the results. Each cell shows the number of times slower that <>> is in comparison to using a block.
|10 Elements||100 Elements||1,000 Elements||Ruby 1.8.7||2.24||1.56||1.34|
In Ruby 1.9.2, the performance of the two forms is very close. In fact, <>> is actually faster for longer arrays.
What I found most interesting, though, was how much larger the performance penalty for using <>> is in JRuby, Rubinius, and MacRuby. I will keep that in the back of my mind when I'm writing code that may be used in those environments.