Why string handling matters in Kotlin - Performance Analysis
When working with strings, it is important to know how the time it takes to handle them changes as the string gets longer.
We want to understand how operations like searching, concatenating, or modifying strings grow with input size.
Analyze the time complexity of the following code snippet.
fun countChar(s: String, c: Char): Int {
var count = 0
for (ch in s) {
if (ch == c) {
count++
}
}
return count
}
This code counts how many times a character appears in a string by checking each character one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character in the string.
- How many times: Once for every character in the string.
As the string gets longer, the number of characters to check grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the length of the string.
Time Complexity: O(n)
This means the time to count characters grows in a straight line as the string gets longer.
[X] Wrong: "Checking a character in a string is always instant no matter the string size."
[OK] Correct: Because the program must look at each character one by one, longer strings take more time.
Understanding how string operations grow helps you write efficient code and explain your thinking clearly in interviews.
"What if we used a built-in function that searches for a character instead of looping manually? How would the time complexity change?"