Basic data types in Go - Time & Space Complexity
When working with basic data types in Go, it's helpful to know how fast operations run.
We want to see how the time to do simple tasks changes as the input size grows.
Analyze the time complexity of the following code snippet.
package main
func sumInts(numbers []int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
This code adds up all numbers in a list of integers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number to total inside a loop.
- How many times: Once for each number in the list.
As the list gets longer, the time to add all numbers grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input list gets bigger.
[X] Wrong: "Adding numbers is always instant, no matter how many there are."
[OK] Correct: Even simple addition takes time, and doing it many times adds up as the list grows.
Understanding how basic operations scale helps you explain code efficiency clearly and confidently.
"What if we changed the list to a fixed size array? How would the time complexity change?"