Unlike other languages, strings in ruby are mutable (meaning they can be altered without needing
to create a new instance).
In languages where strings are immutable, the efficient way to build strings is to use some form
of mutable objets like an Array to hold the parts of the string to built and concatenate them at the end.Thats why Java has a StringBuffer class to tackle exactly the such problem.
In ruby there are multiple ways to concatenate strings:
+= operation builds a brand new string and assigns that new string to first_string. Lets take a closer look at the memory locations where the strings are stored at:
As you can notice first_string now points to a totally different memory location, meaning that
its a new string.
On the other side << keeps appending to the very same string without needing to create a new instance.
Now lets take a look at its memory state:
We can also see the results from the following benchmarks:
If you look at the last column you will notice the total amount of time it took each way
of building strings.