Why conditional logic is needed in Go - Performance Analysis
Conditional logic helps programs decide what to do next based on different situations.
We want to see how adding conditions affects how long a program takes to run.
Analyze the time complexity of the following code snippet.
func checkNumber(n int) string {
if n > 0 {
return "Positive"
} else if n < 0 {
return "Negative"
} else {
return "Zero"
}
}
This code checks if a number is positive, negative, or zero and returns a message.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single conditional checks (if-else statements)
- How many times: Exactly once per function call
Each time the function runs, it does a few checks regardless of the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The number of checks stays the same no matter the input size.
Time Complexity: O(1)
This means the time to run the code does not grow with input size; it stays constant.
[X] Wrong: "More conditions always make the program slower as input grows."
[OK] Correct: Conditions run once per call and do not repeat with input size, so they do not slow down the program as input grows.
Understanding how conditions affect time helps you explain your code clearly and shows you know when code speed changes or stays the same.
"What if we added a loop inside the conditional blocks? How would the time complexity change?"