Array length in Go - Time & Space Complexity
We want to understand how long it takes to find the length of an array in Go.
Does the time change if the array is bigger or smaller?
Analyze the time complexity of the following code snippet.
package main
import "fmt"
func main() {
arr := [5]int{1, 2, 3, 4, 5}
length := len(arr)
fmt.Println(length)
}
This code creates an array and gets its length using the built-in len function.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the array length property.
- How many times: Exactly once, no loops or traversals.
Getting the length does not depend on how big the array is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The operation count stays the same no matter the array size.
Time Complexity: O(1)
This means getting the length of an array takes the same amount of time no matter how big the array is.
[X] Wrong: "Getting the length of an array takes longer if the array is bigger because it counts each item."
[OK] Correct: The length is stored as a property, so Go does not count items each time. It just reads the stored value instantly.
Knowing that array length access is very fast helps you understand what operations are costly and which are not. This skill helps you explain your code clearly in interviews.
"What if we used a slice instead of an array? Would getting the length still be as fast?"