Handling errors in Go - Time & Space Complexity
When we handle errors in Go, we often check if something went wrong and then decide what to do next.
We want to see how the time it takes to run the code changes as the input size grows.
Analyze the time complexity of the following code snippet.
func process(items []int) error {
for _, item := range items {
if err := doSomething(item); err != nil {
return err
}
}
return nil
}
func doSomething(n int) error {
// pretend this does some work
return nil
}
This code goes through a list of items and tries to do something with each one. If an error happens, it stops and returns that error.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list and calling
doSomething. - How many times: Up to once for each item in the list, until an error occurs or all items are processed.
As the number of items grows, the code checks each one until it finds an error or finishes all.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 calls to doSomething |
| 100 | Up to 100 calls to doSomething |
| 1000 | Up to 1000 calls to doSomething |
Pattern observation: The work grows roughly in a straight line with the number of items, unless an error stops the loop early.
Time Complexity: O(n)
This means the time to run grows directly with the number of items we process.
[X] Wrong: "Handling errors adds extra loops or makes the code slower in a complex way."
[OK] Correct: The error check happens inside the same loop and stops early if needed, so it does not add extra loops or change the main growth pattern.
Understanding how error handling affects time helps you write clear and efficient code, a skill that shows you think about both correctness and performance.
"What if doSomething itself had a loop inside? How would the time complexity change?"