If-else statements in Blockchain / Solidity - Time & Space Complexity
We want to see how the time it takes to run if-else statements changes as the input changes in blockchain code.
Are these statements making the program slower when inputs grow?
Analyze the time complexity of the following code snippet.
function checkBalance(address user) {
if (balanceOf(user) > 1000) {
return "Rich";
} else {
return "Not rich";
}
}
This code checks if a user's balance is greater than 1000 and returns a message based on that.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single if-else check.
- How many times: Exactly once per function call.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: Exactly one check per function call, independent of input size, so operations remain constant.
Time Complexity: O(1)
This means the time remains constant regardless of the input size.
[X] Wrong: "If-else statements scale linearly with input size like O(n)."
[OK] Correct: There are no loops or repetitions; the if-else executes exactly once per call, so it's O(1).
Understanding how simple decisions add up helps you explain code efficiency clearly and confidently.
"What if we added a loop inside the if-else? How would the time complexity change?"