String concatenation vs templates in Kotlin - Performance Comparison
We want to see how the time to build strings changes as the input grows.
How does using + versus templates affect the work done?
Analyze the time complexity of the following code snippet.
fun buildStringConcat(words: List): String {
var result = ""
for (word in words) {
result += word
}
return result
}
fun buildStringTemplate(words: List): String {
return words.joinToString(separator = "") { "$it" }
}
This code builds one big string from a list of words using two methods: repeated + concatenation and string templates with joinToString.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each word to add it to the result string.
- How many times: Once for each word in the list (n times).
As the list grows, the work to add each word changes depending on the method.
| Input Size (n) | Approx. Operations for Concatenation | Approx. Operations for Templates |
|---|---|---|
| 10 | About 55 (adding strings repeatedly) | About 10 (joining once) |
| 100 | About 5050 (much more work) | About 100 (joining once) |
| 1000 | About 500500 (very large work) | About 1000 (joining once) |
Pattern observation: Repeated + concatenation grows much faster because each addition copies the whole string so far, while templates join all at once.
Time Complexity: O(n²) for concatenation, O(n) for templates
Repeated + concatenation takes more time as the string grows, but templates handle all words in a single pass.
[X] Wrong: "Using + to add strings is always fast and simple, so it doesn't matter for performance."
[OK] Correct: Each + creates a new string copying old content, so time grows quickly with input size, making it slow for many additions.
Understanding how string building scales helps you write code that stays fast as data grows, a skill valued in many coding challenges.
"What if we used a StringBuilder instead of + for concatenation? How would the time complexity change?"