0
0
Goprogramming~5 mins

Handling errors in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Handling errors
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of items grows, the code checks each one until it finds an error or finishes all.

Input Size (n)Approx. Operations
10Up to 10 calls to doSomething
100Up to 100 calls to doSomething
1000Up 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.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly with the number of items we process.

Common Mistake

[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.

Interview Connect

Understanding how error handling affects time helps you write clear and efficient code, a skill that shows you think about both correctness and performance.

Self-Check

"What if doSomething itself had a loop inside? How would the time complexity change?"