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?"
Practice
Solution
Step 1: Understand string concatenation
Concatenation joins strings using the + operator and requires converting non-string variables to strings explicitly.Step 2: Understand string templates
Templates allow inserting variables directly inside strings using the $ symbol, making code cleaner and easier.Final Answer:
Concatenation uses + to join strings; templates insert variables with $ inside strings. -> Option BQuick Check:
Concatenation vs templates = C [OK]
- Thinking templates need explicit conversion
- Believing concatenation is always faster
- Confusing syntax of templates and concatenation
name into a string using templates?Solution
Step 1: Recall string template syntax
In Kotlin, to insert a variable inside a string, use $variable or ${variable} if expression is needed.Step 2: Identify correct usage for variable insertion
For simple variables, $name works, but to be safe and clear, especially in complex expressions, ${name} is preferred.Final Answer:
"Hello, ${name}!" -> Option CQuick Check:
Variable insertion = ${name} [OK]
- Using curly braces without $
- Using + inside templates
- Forgetting $ before variable
val age = 25
println("Age: " + age + " years")
println("Age: $age years")Solution
Step 1: Evaluate first println with concatenation
"Age: " + age + " years" converts age (25) to string and concatenates, resulting in "Age: 25 years".Step 2: Evaluate second println with template
"Age: $age years" inserts the value of age (25) directly, producing "Age: 25 years".Final Answer:
Age: 25 years Age: 25 years -> Option AQuick Check:
Concatenation and template output same = A [OK]
- Expecting $age to print literally in templates
- Confusing variable name with value
- Missing conversion in concatenation
val score = 90
println("Your score is: $score") + " points"Solution
Step 1: Analyze the println statement
println("Your score is: $score") prints the string with the variable inserted correctly.Step 2: Check the use of + operator
The + " points" is outside the println call, so it tries to add a string to the Unit result of println, causing an error.Final Answer:
The + operator is used incorrectly outside println. -> Option AQuick Check:
Operator placement error = B [OK]
- Thinking templates need curly braces always
- Adding + after println call
- Expecting semicolon in Kotlin
val name = "Anna" and val age = 30. Which code snippet correctly produces the output Hello, Anna! You are 30 years old.?Solution
Step 1: Check concatenation approach
println("Hello, " + name + "! You are " + age + " years old.") uses concatenation with + operators and works but is less clean.Step 2: Check template approaches
String templates using $variable and ${variable} syntax are both correct: simple $variable vs ${variable}, both valid and produce the same output.Step 3: Determine correct options
Since both string template syntaxes produce the correct output, the option indicating both are correct is the answer.Final Answer:
Both B and C -> Option DQuick Check:
Templates with $ or ${} = D [OK]
- Thinking only one template syntax is correct
- Confusing concatenation with templates
- Missing quotes around strings
Ready to prove it?
Pass the test and this pattern moves unknown
