Creating struct values in Go - Performance & Efficiency
Let's see how the time it takes to create struct values changes as we create more of them.
We want to know how the work grows when making many struct values.
Analyze the time complexity of the following code snippet.
package main
type Point struct {
X, Y int
}
func createPoints(n int) []Point {
points := make([]Point, n)
for i := 0; i < n; i++ {
points[i] = Point{X: i, Y: i * 2}
}
return points
}
This code creates a slice of n struct values, each with two integer fields.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop that creates and assigns each struct value.
- How many times: Exactly
ntimes, once for each struct.
Each time we increase n, we create more structs one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 struct creations |
| 100 | 100 struct creations |
| 1000 | 1000 struct creations |
Pattern observation: The work grows directly with the number of structs created.
Time Complexity: O(n)
This means the time to create structs grows in a straight line as you make more of them.
[X] Wrong: "Creating structs is instant and does not depend on how many we make."
[OK] Correct: Each struct takes some time to create, so more structs mean more total time.
Understanding how creating many struct values affects time helps you reason about program speed and efficiency in real tasks.
"What if we changed the struct to include another nested struct? How would the time complexity change?"