0
0
Kotlinprogramming~5 mins

String concatenation vs templates in Kotlin - Performance Comparison

Choose your learning style9 modes available
Time Complexity: String concatenation vs templates
O(n²) for concatenation, O(n) for templates
Understanding Time Complexity

We want to see how the time to build strings changes as the input grows.

How does using + versus templates affect the work done?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

As the list grows, the work to add each word changes depending on the method.

Input Size (n)Approx. Operations for ConcatenationApprox. Operations for Templates
10About 55 (adding strings repeatedly)About 10 (joining once)
100About 5050 (much more work)About 100 (joining once)
1000About 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.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how string building scales helps you write code that stays fast as data grows, a skill valued in many coding challenges.

Self-Check

"What if we used a StringBuilder instead of + for concatenation? How would the time complexity change?"