Img source: medium.com

It is very difficult to think about an application that does not have any string data type. Names, emails, object attributes, etc. are very common. Knowing their wide usages, it is obvious that we should at least learn the best practices about them. I recently learned about the difference between the efficiency of two similar string functions, which was a bit surprising and that made me write this article. Although both methods do the concatenation of strings, there is a big difference in their performance.

The method “+” can be called by a string and have another string as an argument (which is made possible by Ruby’s syntactic sugar). Another method that has the same function is “<<”. In cases when we need to form new strings by using other strings, these are the methods that we may usually use. However, although they may give you the same result, concat function is a lot faster in this regard.

Let’s take an example and see the difference in practice. I am going to use the same code and output from Grey Blake’s blog where I also learned about these differences:


N = 1000
BASIC_LENGTH = 10

5.times do |factor|
  length = BASIC_LENGTH * (10 ** factor)
  puts "_" * 60 + "\nLENGTH: #{length}"

  Benchmark.bm(10, '+= VS <<') do |x|
  concat_report = x.report("+=") do
   str1 = ""
   str2 = "s" * length
   N.times { str1 += str2 }
  end

  modify_report = x.report("<<") do
   str1 = "s"
   str2 = "s" * length
   N.times { str1 << str2 }
  end

  [concat_report / modify_report]
 end
end

One of the main reasons for this difference is their implementation in C: Whenever “+” method is called, a new string object will be created, which is a bit expensive in terms of performance. On the other hand, “<<” simply modifies the existing object that is being used:

first = "first"
second = "second"
first.object_id       # => 16241320

first += second    # first = first + second
first.object_id  # => 16241240, id is changed

first << second
first.object_id  # => 16241240, id is the same

These may seem very minor differences, especially in large applications. However, it is worth knowing that when you are working with a lot of strings, using faster methods can increase the speed and improve the user experience in your applications.

You can learn more about Ruby performance tricks from the Grey Blake’s post. You can also learn about some very simple techniques that can help you optimize your JavaScript code.