Problem

You have several small strings that you need to concatenate into a larger string 

Solution

Obviously there is the concatenation operator that will do the job for us. Evaluate the code below in Dolphin Smalltalk for an example.

'Hello ' , 'world!'

However, if you have more than a couple of strings to concatenate, then that is not very efficient. In Smalltalk strings are constant. Evaluating the code below results in a walkback.

'hello' at: 1 put: $H

So, that means that to concatenate a string you have to create a string big enough to hold both strings and then copy them into it. Not very efficient if you are doing it over and over. The solution is to use streams. The following code should be more efficient.

| aStream aString |
aStream := String new writeStream.
aStream nextPutAll: 'abc'.
aStream nextPutAll: 'def'.
aStream nextPutAll: 'xyz'.
aString:= ''.
aString:= aStream contents.

Umm, I said it should be more efficient, but it isn't. If you put a milliesecondsToRun block around the two pieces of code above you'll find the second is not more efficient if done a number of times. So why's that then? We proved above that it should be.

Well the thing is we constructed the string as String new, and so it has to grow as the concatenations exceed its size. The trick here is that you have to have a rough idea of how big the string will be in the end and dimension the string to an appropriate size; something like the following code would be better

| aStream aString |
aStream := (String new: 10) writeStream.
aStream nextPutAll: 'abc'.
aStream nextPutAll: 'def'.
aStream nextPutAll: 'xyz'.
aString:= ''.
aString:= aStream contents.