Module initialization in Go - Time & Space Complexity
When a Go program starts, it runs special setup code called module initialization.
We want to see how the time to run this setup changes as the program grows.
Analyze the time complexity of the following code snippet.
package main
import "fmt"
var data = initialize()
func initialize() []int {
result := make([]int, 0, 1000)
for i := 0; i < 1000; i++ {
result = append(result, i)
}
return result
}
func main() {
fmt.Println(len(data))
}
This code runs a function to fill a list with 1000 numbers before main starts.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs 1000 times to add numbers to the list.
- How many times: Exactly 1000 times, once for each number added.
Imagine if the loop count changed from 10 to 100 to 1000.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loop steps |
| 100 | 100 loop steps |
| 1000 | 1000 loop steps |
As the number of items to initialize grows, the work grows in a straight line.
Time Complexity: O(n)
This means the setup time grows directly with how many items we prepare before the program runs.
[X] Wrong: "Module initialization always takes constant time no matter what."
[OK] Correct: If the initialization code loops over many items, the time grows with that number, not fixed.
Understanding how setup code scales helps you write programs that start quickly and handle bigger data smoothly.
"What if the initialization function called another function that also loops over the data? How would the time complexity change?"