0
0
Goprogramming~5 mins

Empty interface in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Empty interface
O(n)
Understanding Time Complexity

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

Specifically, how does the program's work grow when it uses empty interfaces with different input sizes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


func sumInts(values []interface{}) int {
    total := 0
    for _, v := range values {
        if num, ok := v.(int); ok {
            total += num
        }
    }
    return total
}
    

This code adds up all integers found inside a slice of empty interfaces.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each element in the slice and checking its type.
  • How many times: Once for every element in the input slice.
How Execution Grows With Input

As the number of elements grows, the program checks each one once.

Input Size (n)Approx. Operations
10About 10 checks and additions
100About 100 checks and additions
1000About 1000 checks and additions

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

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Using empty interfaces makes the code slower in a way that changes the overall time complexity."

[OK] Correct: The empty interface adds a small cost per element for type checking, but the total time still grows linearly with input size.

Interview Connect

Understanding how empty interfaces affect performance helps you write clear and efficient Go code, a useful skill in many programming tasks.

Self-Check

"What if we changed the slice to hold only integers instead of empty interfaces? How would the time complexity change?"