Creating custom packages in Go - Performance & Efficiency
When we create custom packages in Go, we want to know how the time it takes to run our code changes as we use these packages more.
We ask: How does adding package code affect the speed of our program?
Analyze the time complexity of the following code snippet.
package mathutils
func Sum(numbers []int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
This package function sums all numbers in a list by looping through each one once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the input list.
- How many times: Exactly once for each number in the 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 list size doubles the work needed.
Time Complexity: O(n)
This means the time to run grows directly with the number of items we add.
[X] Wrong: "Using a package always makes code slower because it adds extra steps."
[OK] Correct: The package code runs just like any other code, so its speed depends on what it does, not just that it is a package.
Understanding how your package code runs helps you write clear and efficient programs, a skill that shows you know how to build good software.
"What if the Sum function used recursion instead of a loop? How would the time complexity change?"