Relative Performance of Symbol#to_proc in Popular Ruby Implementations

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 Elements100 Elements1,000 Elements
Ruby 1.8.72.241.561.34
REE 1.8.72.491.931.66
Ruby 1.9.21.030.940.95
JRuby 1.5.37.223.183.61
Rubinius 1.1.05.827.556.86
MacRuby 0.7.16.869.809.96

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.


0 Comments