0
0
Goprogramming~5 mins

Passing values vs pointers in Go - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Passing values vs pointers
O(n)
Understanding Time Complexity

When we pass values or pointers in Go, it affects how much work the program does.

We want to see how the time to run changes as the data size grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func processValue(data [1000]int) {
    // Simulate some processing
    for _, v := range data {
        _ = v * 2
    }
}

func processPointer(data *[1000]int) {
    // Simulate some processing
    for _, v := range *data {
        _ = v * 2
    }
}

This code shows two functions: one takes a large array by value, the other by pointer, both loop over the array.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping over 1000 elements in the array.
  • How many times: Exactly 1000 times for each function call.
  • Additional operation for value passing: Copying the entire array once when calling the function.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
10Copy 10 items + loop 10 times
100Copy 100 items + loop 100 times
1000Copy 1000 items + loop 1000 times

Pattern observation: Passing by value adds a copying step that grows with input size, while passing by pointer avoids this copy.

Final Time Complexity

Time Complexity: O(n)

This means the time grows linearly with the size of the data, mainly due to looping and copying when passing by value.

Common Mistake

[X] Wrong: "Passing by pointer always makes the code faster regardless of what happens inside the function."

[OK] Correct: Sometimes the function does more work that dominates time, so the cost of copying might be small compared to processing.

Interview Connect

Understanding how passing values or pointers affects performance helps you write efficient code and explain your choices clearly.

Self-Check

"What if the array size doubled? How would passing by value vs pointer affect the time complexity then?"