Why expressions over statements matters in Kotlin - Performance Analysis
We want to see how choosing expressions instead of statements affects how long code takes to run.
Does using expressions change how the program grows with bigger inputs?
Analyze the time complexity of the following code snippet.
fun maxOfTwo(a: Int, b: Int): Int {
return if (a > b) a else b
}
fun maxOfTwoStatement(a: Int, b: Int): Int {
var max: Int
if (a > b) {
max = a
} else {
max = b
}
return max
}
This code compares two numbers and returns the bigger one, once using an expression and once using statements.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single comparison between two numbers.
- How many times: Exactly once per function call.
Since the functions only compare two numbers once, the work stays the same no matter what.
| Input Size (n) | Approx. Operations |
|---|---|
| 2 | 1 comparison |
| 10 | 1 comparison |
| 1000 | 1 comparison |
Pattern observation: The number of operations does not grow with input size here.
Time Complexity: O(1)
This means the time to run the code stays the same no matter how big the input is.
[X] Wrong: "Using expressions always makes code faster than statements."
[OK] Correct: Both expressions and statements can run in the same time; the difference is often about style and clarity, not speed.
Understanding how expressions and statements affect code helps you write clear and efficient programs, a skill valued in many coding challenges and real projects.
"What if we compared three numbers instead of two? How would the time complexity change?"