0
0
Goprogramming~5 mins

Writing basic test functions in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Writing basic test functions
O(n)
Understanding Time Complexity

When writing basic test functions in Go, it is important to understand how the time taken grows as tests run on more cases.

We want to know how the number of tests affects the total time to complete all tests.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func TestSum(t *testing.T) {
    for i := 0; i < len(testCases); i++ {
        got := Sum(testCases[i].input)
        if got != testCases[i].expected {
            t.Errorf("Sum() = %d; want %d", got, testCases[i].expected)
        }
    }
}
    

This test function runs through a list of test cases and checks if the Sum function returns the expected result for each.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each test case once.
  • How many times: Exactly once per test case in the list.
How Execution Grows With Input

As the number of test cases grows, the total time grows in direct proportion.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: Doubling the number of test cases roughly doubles the total work done.

Final Time Complexity

Time Complexity: O(n)

This means the time to run all tests grows linearly with the number of test cases.

Common Mistake

[X] Wrong: "Running more tests won't affect total time much because each test is small."

[OK] Correct: Even small tests add up, so more tests mean more total time in a straight line.

Interview Connect

Understanding how test functions scale helps you write efficient tests and reason about testing time in real projects.

Self-Check

What if we added nested loops inside each test case? How would the time complexity change?