0
0
Goprogramming~5 mins

Creating struct values in Go - Performance & Efficiency

Choose your learning style9 modes available
Time Complexity: Creating struct values
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop that creates and assigns each struct value.
  • How many times: Exactly n times, once for each struct.
How Execution Grows With Input

Each time we increase n, we create more structs one by one.

Input Size (n)Approx. Operations
1010 struct creations
100100 struct creations
10001000 struct creations

Pattern observation: The work grows directly with the number of structs created.

Final Time Complexity

Time Complexity: O(n)

This means the time to create structs grows in a straight line as you make more of them.

Common Mistake

[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.

Interview Connect

Understanding how creating many struct values affects time helps you reason about program speed and efficiency in real tasks.

Self-Check

"What if we changed the struct to include another nested struct? How would the time complexity change?"