Why ranges simplify iteration in Kotlin - Performance Analysis
When we use ranges to loop in Kotlin, it helps us write simpler code. But how does this affect how long the program takes to run?
We want to see how the number of steps changes as the range size grows.
Analyze the time complexity of the following code snippet.
for (i in 1..n) {
println(i)
}
This code prints numbers from 1 up to n using a range.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs once for each number in the range.
- How many times: Exactly n times, where n is the size of the range.
As n gets bigger, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The steps increase directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time it takes grows in a straight line with the size of the range.
[X] Wrong: "Using a range makes the loop run faster than a normal loop."
[OK] Correct: The range just makes the code easier to write and read, but the loop still runs once for each number.
Understanding how loops grow with input size is a key skill. Using ranges is a neat way to write loops, and knowing their time cost helps you explain your code clearly.
"What if we changed the range to step by 2 instead of 1? How would the time complexity change?"