Test-driven basics in Go - Time & Space Complexity
When writing tests first, it is important to know how the time your tests take grows as your code runs on bigger inputs.
We want to see how the test and code execution time changes when input size changes.
Analyze the time complexity of the following test-driven code snippet.
func Sum(nums []int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func TestSum(t *testing.T) {
result := Sum([]int{1, 2, 3, 4})
if result != 10 {
t.Errorf("Expected 10, got %d", result)
}
}
This code defines a function that adds numbers in a list and a test that checks if it works correctly.
Look for loops or repeated steps in the code.
- Primary operation: Looping through each number in the input list to add it.
- How many times: Once for each number in the list.
As the list gets bigger, the time to add all numbers grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: Doubling the input doubles the work because each number is added once.
Time Complexity: O(n)
This means the time grows directly with the number of items you add.
[X] Wrong: "The test time stays the same no matter how many numbers I add."
[OK] Correct: The test runs the function, and the function adds each number, so more numbers mean more work and more time.
Understanding how test and code time grows helps you write better tests and code that work well even with bigger inputs.
"What if the Sum function used recursion instead of a loop? How would the time complexity change?"