String Building
String building is joining many small pieces into one longer string. The method you choose changes how much extra work the program does.
Repeated + builds many in-between strings
Each + step makes a fresh string. This program joins ab three times and prints the string and its length.
@main def main(): Unit =
var result = ""
var i = 1
while i <= 3 do
result = result + "ab"
i = i + 1
println(result)
println(result.length)A StringBuilder grows one string
A StringBuilder collects pieces without making a new string per piece. This program appends ab three times and prints the string and its length.
@main def main(): Unit =
val builder = new StringBuilder
var i = 1
while i <= 3 do
builder.append("ab")
i = i + 1
println(builder.toString)
println(builder.toString.length)Both methods reach the same string
The two methods differ in work, not in result. This program builds the string both ways and prints whether they match, plus the length.
@main def main(): Unit =
var result = ""
var i = 1
while i <= 3 do
result = result + "ab"
i = i + 1
val builder = new StringBuilder
var j = 1
while j <= 3 do
builder.append("ab")
j = j + 1
println(result == builder.toString)
println(result.length)Example
@main def main(): Unit =
val parts = List("Scala", " ", "is", " ", "fast")
var joined = ""
var i = 0
while i < parts.size do
joined = joined + parts(i)
i = i + 1
val builder = new StringBuilder
var j = 0
while j < parts.size do
builder.append(parts(j))
j = j + 1
println(builder.toString)
println(builder.toString.length)
println(joined == builder.toString)Key points
- String: A string is a sequence of characters held as text.
- Concatenation: Joining strings with + builds a new string each time.
- Mutable: A mutable value can change in place after it is created.
- StringBuilder: A StringBuilder is a mutable buffer that collects pieces and builds one string at the end.
- Allocation: Creating a new string value is an allocation, and repeated + allocates many in-between strings.
- Length: The length of a string is the count of its characters.
In this example, the parts are joined once with + and once with a StringBuilder, and the program prints the built string, its length of 13, and true for the two results matching.
Note
In Scala, a plain String cannot change, so each + step must make a new string.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
You join hundreds of pieces inside a loop. Which method avoids many in-between strings?