Benchmarking Ruby String interpolation, concatenation and appending

July 14, 2008 at 23:28

Filed under: Computing — Pistos @ 23:28

I recently came across 6 Optimization Tips for Ruby MRI. One of the tips provided is to use string interpolation instead of concatenation. I set out to determine whether or not we really get any performance boost out of this, and, if so, how much.

My test code makes use of better-benchmark, my Ruby library for statistically correct benchmarking.

Here is a table summarizing the detailed results. By “append” I mean usage of the << operator; by “concatenate” I mean usage of the + operator.

Comparison Improvement Statistically
Significant
Single Quote Append vs. Double Quote Append 0.4% no
Append vs. Interpolation 3.4% no
Two Appends vs. Interpolation 21.0% yes
Concatenation vs. Interpolation 8.4% yes
Two Concatenations vs. Interpolation 29.0% yes
Concatenation vs. Append 7.8% no
Several Concatenations vs. Several Appends 36.3% yes

The first thing to note is that the apparent performance improvement of 3.4% in using interpolation instead of appending is not statistically significant. That is, the data do not provide evidence supporting the claim that interpolation is better (or worse) than appending. However, in fairness, doing two appends makes the difference significant.

We also see that concatenation is slower than appending, as is often cited. But, again, we cannot conclude this is the case when comparing only a single concatenate versus a single append. The difference is only pronounced when doing multiple concatenations or appends in a single Ruby line.

Overall, there appears to be good reason to use interpolation by default, and append or concatenate only under special circumstances. In the end, though, you should be benchmarking larger sections of your code, such as measuring the time taken to render a web page. Doing even a hundred individual concatenations takes just a tiny fraction of a second, and a performance improvement of a few microseconds isn’t going to mean much when you have a large bottleneck elsewhere, such as in your database queries.

Share This

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

You may use Markdown syntax in your comment.

Powered by WP Hashcash

Powered by WordPress.
Close
E-mail It
Socialized through Gregarious 42