Why extensions add without modifying in Kotlin - Performance Analysis
When we add new features using extensions in Kotlin, we want to know how this affects the program's speed.
We ask: How does adding extensions change the work the program does as input grows?
Analyze the time complexity of the following code snippet.
fun List<Int>.sumOfSquares(): Int {
var sum = 0
for (num in this) {
sum += num * num
}
return sum
}
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
println(numbers.sumOfSquares())
}
This code adds a new function to List<Int> that calculates the sum of squares of its elements without changing the original List class.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element of the list to calculate its square and add it.
- How many times: Once for each element in the list (n times).
As the list gets bigger, the function does more work by repeating the square and add steps for each new item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 squares and adds |
| 100 | About 100 squares and adds |
| 1000 | About 1000 squares and adds |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n)
This means the time to run the extension grows in a straight line with the size of the list.
[X] Wrong: "Adding an extension function changes the original class and makes it slower overall."
[OK] Correct: Extensions add new functions without changing the original class code, so they only add the cost of their own operations, not extra hidden work.
Understanding how extensions work helps you explain how new features can be added safely without slowing down existing code, a useful skill in many coding tasks.
What if the extension function called another function inside a nested loop? How would the time complexity change?