0
0
Kotlinprogramming~5 mins

Infix functions in DSLs in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Infix functions in DSLs
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code with infix functions in Kotlin DSLs changes as the input grows.

Specifically, how does using infix functions affect the number of steps the program takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Builder {
    private val items = mutableListOf()

    infix fun add(item: String) {
        items.add(item)
    }

    fun build() = items
}

fun main() {
    val builder = Builder()
    builder add "apple"
    builder add "banana"
    builder add "cherry"
    val result = builder.build()
}
    

This code defines a simple builder using an infix function to add items to a list, then builds the list.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding items to a list using the infix add function.
  • How many times: Once per item added (here 3 times, but can be n times).
How Execution Grows With Input

Each time we add an item, the program does one add operation.

Input Size (n)Approx. Operations
1010 add operations
100100 add operations
10001000 add operations

Pattern observation: The number of operations grows directly with the number of items added.

Final Time Complexity

Time Complexity: O(n)

This means the time to add items grows in a straight line as you add more items.

Common Mistake

[X] Wrong: "Using infix functions makes the code run faster or slower by itself."

[OK] Correct: Infix functions only change how code looks, not how many steps it takes. The time depends on what the function does, not the infix style.

Interview Connect

Understanding how syntax choices like infix functions affect performance helps you explain your code clearly and confidently in real projects and interviews.

Self-Check

What if the add function also checked for duplicates before adding? How would the time complexity change?