Why Go is widely used - Performance Analysis
We want to understand how Go handles tasks efficiently as programs grow bigger.
How does Go's design affect the speed of running code when input size changes?
Analyze the time complexity of the following Go code snippet.
package main
import "fmt"
func sum(numbers []int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
func main() {
nums := []int{1, 2, 3, 4, 5}
fmt.Println(sum(nums))
}
This code adds up all numbers in a list and prints the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Once for every number in the input list.
As the list gets bigger, 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: Doubling the input doubles the work needed.
Time Complexity: O(n)
This means the time to finish grows directly with the size of the input list.
[X] Wrong: "The program runs in the same time no matter how big the list is."
[OK] Correct: The loop must visit each item, so more items mean more time.
Knowing how Go handles loops and input size helps you explain why Go is fast and simple for many tasks.
"What if we changed the loop to run inside another loop over the same list? How would the time complexity change?"