0
0
Kotlinprogramming~5 mins

This vs it receiver difference in Kotlin - Performance Comparison

Choose your learning style9 modes available
Time Complexity: This vs it receiver difference
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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.

Identify Repeating Operations

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

As the list gets bigger, the number of additions grows directly with the list size.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows evenly as the list grows, no matter if this or it is used.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

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.

Self-Check

What if we replaced the forEach loop with a recursive function using this or it? How would the time complexity change?