Zero values in Go - Time & Space Complexity
We want to see how the time to run code changes when using zero values in Go.
Does initializing variables with zero values affect how long the program takes?
Analyze the time complexity of the following code snippet.
package main
func initializeSlice(n int) []int {
s := make([]int, n) // slice with zero values
for i := 0; i < n; i++ {
s[i] = 0 // explicitly setting zero value
}
return s
}
This code creates a slice of size n and sets each element to zero explicitly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for loop that sets each element to zero.
- How many times: It runs n times, once for each element in the slice.
As the slice size n grows, the number of operations grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: Doubling the input doubles the work because each element is set once.
Time Complexity: O(n)
This means the time to run grows directly with the size of the slice.
[X] Wrong: "Since the slice is filled with zero values by default, the loop does nothing extra and takes no time."
[OK] Correct: Even if zero values exist by default, the loop still runs n times doing an assignment, which takes time proportional to n.
Understanding how loops over zero values affect time helps you explain simple but important performance ideas clearly.
"What if we removed the loop that sets zero values explicitly? How would the time complexity change?"