Is the general advice still to prefer string interpolation over concatentation even for only a couple short strings?

I was adding " " (one space) not empty string.

+ between two strings basically does same thing as interpolation - get sizes of two strings, allocate sum of them, copy buffers.
But when you use first_str + second_string + " " (in any order, but empty strings are perhaps removed by optimizer so all three must be nonempty) interpolation become much faster - it can count all three sizes at once but + can only work step by step (concatenate first two strings, then add third one).

So if you just want concatenate two strings - you can do it with +. But once you need to concatenate three or more - interpolation is much faster and memory efficient.
My benchmark:

require "benchmark"

str1 = "something"
str2 = "something else"

Benchmark.ips do |bench|
  bench.report("str1+str2") { str1 + str2 }
  bench.report("interpolate") { "#{str1}#{str2}" }
  bench.report("str1+' '+str2") { str1 +" "+ str2 }
  bench.report("interpolate2") {  "#{str1} #{str2}" }
  bench.report("str1+str2+' '") { str1 + str2 + " " }
  bench.report("str1+''+str2") { str1 +""+ str2 }
  bench.report("str1+str2+''") { str1 + str2 + "" }
end

results:

    str1+str2   6.22M (160.83ns) (± 4.41%)  48.0B/op   1.03× slower
  interpolate   6.35M (157.38ns) (± 2.65%)  48.0B/op   1.01× slower
str1+' '+str2   3.84M (260.61ns) (± 1.61%)  80.0B/op   1.67× slower
 interpolate2   6.26M (159.71ns) (± 1.74%)  48.0B/op   1.03× slower
str1+str2+' '   3.27M (306.05ns) (± 1.69%)  96.0B/op   1.97× slower
 str1+''+str2   6.40M (156.34ns) (± 1.93%)  48.0B/op   1.00× slower
 str1+str2+''   6.43M (155.59ns) (± 2.07%)  48.0B/op        fastest
2 Likes