Infix functions in DSLs in Kotlin - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Adding items to a list using the infix
addfunction. - How many times: Once per item added (here 3 times, but can be n times).
Each time we add an item, the program does one add operation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 add operations |
| 100 | 100 add operations |
| 1000 | 1000 add operations |
Pattern observation: The number of operations grows directly with the number of items added.
Time Complexity: O(n)
This means the time to add items grows in a straight line as you add more items.
[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.
Understanding how syntax choices like infix functions affect performance helps you explain your code clearly and confidently in real projects and interviews.
What if the add function also checked for duplicates before adding? How would the time complexity change?