Go programming
performance optimization
len() function
multiple calls
coding best practices

Go multiple len calls vs performance?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

In Go, calling len multiple times is usually not a performance problem. For slices, maps, strings, arrays, and channels, len is designed to be fast and typically constant time. Most optimization effort should focus on allocations, algorithm complexity, and I O before worrying about repeated len calls.

Understand len Cost by Type

len does not iterate through collection elements. It reads metadata that is already stored with the value. That means repeated calls inside loops are often negligible.

go
1package main
2
3import "fmt"
4
5func main() {
6    s := []int{10, 20, 30, 40}
7    m := map[string]int{"a": 1, "b": 2}
8    str := "golang"
9
10    fmt.Println(len(s))
11    fmt.Println(len(m))
12    fmt.Println(len(str))
13}

For strings, len returns byte count, not rune count. That is a correctness concern, not a performance issue.

Write Readable Loops First

Loop code should prioritize clarity. Caching len into a variable is fine when it improves readability, but doing it for micro optimization alone is rarely useful.

go
1package main
2
3import "fmt"
4
5func sum(values []int) int {
6    total := 0
7    for i := 0; i < len(values); i++ {
8        total += values[i]
9    }
10    return total
11}
12
13func sumCached(values []int) int {
14    total := 0
15    n := len(values)
16    for i := 0; i < n; i++ {
17        total += values[i]
18    }
19    return total
20}
21
22func main() {
23    fmt.Println(sum([]int{1, 2, 3}))
24    fmt.Println(sumCached([]int{1, 2, 3}))
25}

Both versions are acceptable. Choose the one your team finds easier to maintain.

Benchmark If You Suspect a Hot Spot

When code runs in critical paths, use Go benchmarks rather than assumptions.

go
1package main
2
3import "testing"
4
5func BenchmarkLenInline(b *testing.B) {
6    values := make([]int, 1024)
7    b.ResetTimer()
8    for n := 0; n < b.N; n++ {
9        sum := 0
10        for i := 0; i < len(values); i++ {
11            sum += values[i]
12        }
13        _ = sum
14    }
15}
16
17func BenchmarkLenCached(b *testing.B) {
18    values := make([]int, 1024)
19    b.ResetTimer()
20    for n := 0; n < b.N; n++ {
21        sum := 0
22        limit := len(values)
23        for i := 0; i < limit; i++ {
24            sum += values[i]
25        }
26        _ = sum
27    }
28}

Run with go test -bench . and compare results on your target environment.

Focus on Bigger Performance Wins

In real services, latency is more affected by network calls, JSON encoding, memory churn, and lock contention than by len invocation count. Use profiling tools such as pprof to locate real bottlenecks before refactoring loops.

Consider Range Loops and Compiler Optimizations

In many cases a for range loop is more idiomatic than index based loops and lets the compiler optimize bounds checks effectively. Choose loop style based on readability first, then benchmark if the path is performance critical.

go
1sum := 0
2for _, v := range values {
3    sum += v
4}

Keep profiling data alongside benchmark results for long term tuning decisions.

Common Pitfalls

One pitfall is misusing len on UTF 8 strings when counting characters. Use utf8.RuneCountInString if character count is required.

Another issue is premature optimization that harms readability. Complex loop rewrites for tiny wins can make bugs harder to detect.

A third issue is benchmarking without realistic data sizes. Small synthetic inputs can produce misleading conclusions.

Summary

  • Multiple len calls in Go are typically cheap and not a hot spot.
  • Prioritize readable loops unless profiling proves otherwise.
  • Use benchmarks and pprof before performance refactors.
  • Remember len on strings counts bytes, not Unicode characters.
  • Invest effort in algorithm and allocation improvements first.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.