Empty interface in Go - Time & Space 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?
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 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.
As the number of elements grows, the program checks each one once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and additions |
| 100 | About 100 checks and additions |
| 1000 | About 1000 checks and additions |
Pattern observation: The work grows directly with the number of elements.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input size grows.
[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.
Understanding how empty interfaces affect performance helps you write clear and efficient Go code, a useful skill in many programming tasks.
"What if we changed the slice to hold only integers instead of empty interfaces? How would the time complexity change?"