In Ternary operator, a person wanting to join ["foo", "bar", "baz"] with commas and an “and” cited The Ruby Cookbook as saying
If efficiency is important to you,
don’t build a new string when you can
append items onto an existing string.
[And so on]… Use str << var1 << ‘ ‘
<< var2 instead.
But the book was written in 2006.
Is using appending (ie <<) still the fastest way to build a large string given an array of smaller strings, in all major implementations of Ruby?
Use
Array#joinwhen you can, andString#<<when you can’t.The problem with using
String#+is that it must create an intermediary (unwanted) string object, whileString#<<mutates the original string. Here are the time results (in seconds) of joining 1,000 strings with", "1,000 times, viaArray#join,String#+, andString#<<:Here’s the benchmarking code:
Results obtained on Ubuntu under RVM. Results from Ruby 1.9.2p180 from RubyInstaller on Windows are similar to the 1.9.2 shown above.