This vs it receiver difference in Kotlin - Performance Comparison
We want to understand how the use of different receivers like this and it affects the number of operations in Kotlin code.
Specifically, how does choosing one receiver over the other change the work done as input grows?
Analyze the time complexity of the following Kotlin code using this and it receivers.
fun List<Int>.sumWithThis(): Int {
var total = 0
this.forEach { total += it }
return total
}
fun List<Int>.sumWithIt(): Int {
var total = 0
for (item in this) {
total += item
}
return total
}
Both functions add up all numbers in a list, but use this and it differently.
Look at what repeats as the list size grows.
- Primary operation: Adding each number to
total. - How many times: Once for every item in the list.
As the list gets bigger, the number of additions grows directly with the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows evenly as the list grows, no matter if this or it is used.
Time Complexity: O(n)
This means the time to add all numbers grows in a straight line with the list size, regardless of using this or it.
[X] Wrong: "Using this is slower or faster than it because it changes how many times the code runs."
[OK] Correct: Both receivers just name the current item or object. They don't add extra loops or operations. The number of times the code runs depends only on the list size.
Understanding how different ways to refer to data affect performance helps you write clear and efficient Kotlin code. It shows you can focus on what matters most: the size of your data, not small syntax choices.
What if we replaced the forEach loop with a recursive function using this or it? How would the time complexity change?