String Concatenation the Right Way; the Fast and Furious Way

Flatiron School / 15 October 2012

The following is a guest post by Stephen Chen and originally appeared on his blog. Stephen is currently a student a The Flatiron School. You can learn more about him here, or follow him on twitter here.

One of the greatest parts of programming is learning something that blows your mind, a moment where this happens. It’s one of those moments that you realize you are a programming n00b, and that there is always a better way to do things. I had one of these moments recently when I was going through the Ruby Koans. In one of the introductory tests that cover strings you are told to think about string concatenation, and in particular which method is faster when building strings: “+” or ”«”.

The great part about leading questions like that is that you pretty much already know what the answer is going to be. So I went ahead and proved it, just so I could write this blog post. Awesome. There’s a really handy Benchmark class in Ruby that lets you time to execution of blocks of code, so I used that to scientifically prove what we all now know is true: ”«” is faster than “+”.

Here are the results:

As you can see, the ”«” operator is a whole lot faster. It’s faster because “«” alters the original string, whereas “+” has to create a new string, and creation is a more costly operation. This is something that seems really small and insignificant, but performance matters. Like Vin Diesel said, “It doesn’t matter if you win by an inch or a mile. Winning’s winning. Unless you’re not using ‘«’ to build Ruby strings. Then you are losing.”

How to Get Into the Flatiron School Previous Post Contributing to Open Source: A Beginner's Guide (Part 1 of 2) Next Post