# Golang for-range 内部实现

DevFeed: [Golang for-range 内部实现](<https://devfeed.tech/articles/golang-for-range-40986.md>)

Original publisher: [Read original article](<https://blog.joway.io/posts/golang-range-internal/>)

Author: Joway

Published: 2021-01-20T00:00:00Z

Content type: tutorial

Language: zh

Sources: [Random Thoughts](<https://devfeed.tech/sources/random-thoughts.md>)

Topics: [Go Language](<https://devfeed.tech/topics/go-language.md>), [Go](<https://devfeed.tech/topics/go.md>)

Tags: [go](<https://devfeed.tech/tags/go.md>), [golang](<https://devfeed.tech/tags/golang.md>), [range](<https://devfeed.tech/tags/range.md>), [tech](<https://devfeed.tech/tags/tech.md>), [type](<https://devfeed.tech/tags/type.md>)

## AI overview

The article explains how Go's for-range loop is compiled and why it can be much slower than index-based iteration when iterated elements are expensive to copy. It notes that range saves the element length, copies values, and reuses loop variables, recommending a standard for loop for large copy-heavy element types.

## Source excerpt

最近在写一个编解码的功能时发现使用 Golang for-range 会存在很大的性能问题。 假设我们现在有一个 Data 类型表示一个数据包，我们从网络中获取到了 [1024]Data 个数据包，此时我们需要对其进行遍历操作。一般我们会使用 for-i++ 或者 for-range 两种方式遍历，如下代码： type Data [256]byte func BenchmarkForStruct(b *testing.B) { var items [1024]Data var result Data for i := 0; i < b.N; i++ { for k := 0; k < len(items); k++ { result = items[k] } } _ = result } func BenchmarkRangeStruct(b *testing.B) { var items [1024]Data var result Data for i := 0; i < b.N; i++ { for _, item := range items { result = item } } _ = result } 输出结果：