0
0
Goprogramming~5 mins

Why methods are used in Go - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why methods are used
O(n)
Understanding Time Complexity

We want to understand how using methods affects the time it takes for a program to run.

Specifically, we ask: Does calling a method change how the program grows with bigger inputs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


package main

import "fmt"

type Counter struct {
    count int
}

func (c *Counter) Increment() {
    c.count++
}

func main() {
    c := Counter{}
    for i := 0; i < 1000; i++ {
        c.Increment()
    }
    fmt.Println(c.count)
}
    

This code defines a method to increase a count and calls it many times in a loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the Increment method inside a loop.
  • How many times: 1000 times, once per loop iteration.
How Execution Grows With Input

Each time the input (loop count) grows, the number of method calls grows the same way.

Input Size (n)Approx. Operations
1010 method calls
100100 method calls
10001000 method calls

Pattern observation: The number of operations grows directly with the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the input gets bigger.

Common Mistake

[X] Wrong: "Using methods always makes the program slower in a big way."

[OK] Correct: Calling a method is just like running a small piece of code; it doesn't add extra loops or big work by itself.

Interview Connect

Understanding how methods affect time helps you explain your code clearly and shows you know how programs grow with input size.

Self-Check

"What if the Increment method itself had a loop inside? How would the time complexity change?"