Table of Contents
Copy copy problem" >Copy copy problem
性能对比" >性能对比
遍历结构体数组" >遍历结构体数组
结论" >结论
Home Backend Development Golang Handling large arrays in Go: use for range or for loop?

Handling large arrays in Go: use for range or for loop?

Jul 24, 2023 pm 02:47 PM
go for loop

#We know that Go’s syntax is relatively concise. It does not provide C-like support for <span style="font-size: 15px;">while</span>, <span style="font-size: 15px;">do...while</span> and other loop control syntax, while only one statement is retained, that is, the for loop.
for i := 0; i < n; i++ {
    ... ...
}
Copy after login

However, the classic three-stage loop statement needs to obtain the length n of the iteration object. In view of this, in order to make it easier for Go developers to iterate over composite data types, such as array, slice, channel, map, Go provides a variant of the for loop, namely <span style="font-size: 15px;">for range</span> Loop.

Copy copy problem

While range brings convenience, it also brings some troubles to Go beginners. Because users need to understand one thing: in for range, only a copy of the object participates in the loop expression.

func main() {
    var a = [5]int{1, 2, 3, 4, 5}
    var r [5]int

    fmt.Println("original a =", a)

    for i, v := range a {
        if i == 0 {
            a[1] = 12
            a[2] = 13
        }
        r[i] = v
    }

    fmt.Println("after for range loop, r =", r)
    fmt.Println("after for range loop, a =", a)
}
Copy after login

Do you think this code will output the following results?

original a = [1 2 3 4 5]
after for range loop, r = [1 12 13 4 5]
after for range loop, a = [1 12 13 4 5]
Copy after login

但是,实际输出是

original a = [1 2 3 4 5]
after for range loop, r = [1 2 3 4 5]
after for range loop, a = [1 12 13 4 5]
Copy after login

为什么会这样?原因是参与 for range 循环是 range 表达式的副本。也就是说,在上面的例子中,实际上参与循环的是 a 的副本,而不是真正的 a。

为了让大家更容易理解,我们把上面例子中的 for range 循环改写成等效的伪代码形式。

for i, v := range ac { //ac is a value copy of a
    if i == 0 {
        a[1] = 12
        a[2] = 13
    }
    r[i] = v
}
Copy after login

ac 是 Go 临时分配的连续字节序列,与 a 根本不是同一块内存空间。因此,无论 a 如何修改,它参与循环的副本 ac 仍然保持原始值,因此从 ac 中取出的 v 也依然是 a 的原始值,而不是修改后的值。

那么,问题来了,既然 for range 使用的是副本数据,那 for range 会比经典的 for 循环消耗更多的资源并且性能更差吗?

性能对比

基于副本复制问题,我们先使用基准示例来验证一下:对于大型数组,for range 是否一定比经典的 for 循环运行得慢?

package main

import "testing"

func BenchmarkClassicForLoopIntArray(b *testing.B) {
 b.ReportAllocs()
 var arr [100000]int
 for i := 0; i < b.N; i++ {
  for j := 0; j < len(arr); j++ {
   arr[j] = j
  }
 }
}

func BenchmarkForRangeIntArray(b *testing.B) {
 b.ReportAllocs()
 var arr [100000]int
 for i := 0; i < b.N; i++ {
  for j, v := range arr {
   arr[j] = j
   _ = v
  }
 }
}
Copy after login

在这个例子中,我们使用 for 循环和 for range 分别遍历一个包含 10 万个 int 类型元素的数组。让我们看看基准测试的结果

$ go test -bench . forRange1_test.go 
goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i5-8279U CPU @ 2.40GHz
BenchmarkClassicForLoopIntArray-8          47404             25486 ns/op               0 B/op          0 allocs/op
BenchmarkForRangeIntArray-8                37142             31691 ns/op               0 B/op          0 allocs/op
PASS
ok      command-line-arguments  2.978s
Copy after login

从输出结果可以看出,for range 的确会稍劣于 for 循环,当然这其中包含了编译器级别优化的结果(通常是静态单赋值,或者 SSA 链接)。

让我们关闭优化开关,再次运行压力测试。

 $ go test -c -gcflags &#39;-N -l&#39; . -o forRange1.test
 $ ./forRange1.test -test.bench .
 goos: darwin
goarch: amd64
pkg: workspace/example/forRange
cpu: Intel(R) Core(TM) i5-8279U CPU @ 2.40GHz
BenchmarkClassicForLoopIntArray-8           6734            175319 ns/op               0 B/op          0 allocs/op
BenchmarkForRangeIntArray-8                 5178            242977 ns/op               0 B/op          0 allocs/op
PASS
Copy after login

当没有编译器优化时,两种循环的性能都明显下降, for range 下降得更为明显,性能也更加比经典 for 循环差。

遍历结构体数组

上述性能测试中,我们的遍历对象类型是 int 值的数组,如果我们将 int 元素改为结构体会怎么样?for 和 for range 循环各自表现又会如何?

package main

import "testing"

type U5 struct {
 a, b, c, d, e int
}
type U4 struct {
 a, b, c, d int
}
type U3 struct {
 b, c, d int
}
type U2 struct {
 c, d int
}
type U1 struct {
 d int
}

func BenchmarkClassicForLoopLargeStructArrayU5(b *testing.B) {
 b.ReportAllocs()
 var arr [100000]U5
 for i := 0; i < b.N; i++ {
  for j := 0; j < len(arr)-1; j++ {
   arr[j].d = j
  }
 }
}
func BenchmarkClassicForLoopLargeStructArrayU4(b *testing.B) {
 b.ReportAllocs()
 var arr [100000]U4
 for i := 0; i < b.N; i++ {
  for j := 0; j < len(arr)-1; j++ {
   arr[j].d = j
  }
 }
}
func BenchmarkClassicForLoopLargeStructArrayU3(b *testing.B) {
 b.ReportAllocs()
 var arr [100000]U3
 for i := 0; i < b.N; i++ {
  for j := 0; j < len(arr)-1; j++ {
   arr[j].d = j
  }
 }
}
func BenchmarkClassicForLoopLargeStructArrayU2(b *testing.B) {
 b.ReportAllocs()
 var arr [100000]U2
 for i := 0; i < b.N; i++ {
  for j := 0; j < len(arr)-1; j++ {
   arr[j].d = j
  }
 }
}

func BenchmarkClassicForLoopLargeStructArrayU1(b *testing.B) {
 b.ReportAllocs()
 var arr [100000]U1
 for i := 0; i < b.N; i++ {
  for j := 0; j < len(arr)-1; j++ {
   arr[j].d = j
  }
 }
}

func BenchmarkForRangeLargeStructArrayU5(b *testing.B) {
 b.ReportAllocs()
 var arr [100000]U5
 for i := 0; i < b.N; i++ {
  for j, v := range arr {
   arr[j].d = j
   _ = v
  }
 }
}
func BenchmarkForRangeLargeStructArrayU4(b *testing.B) {
 b.ReportAllocs()
 var arr [100000]U4
 for i := 0; i < b.N; i++ {
  for j, v := range arr {
   arr[j].d = j
   _ = v
  }
 }
}

func BenchmarkForRangeLargeStructArrayU3(b *testing.B) {
 b.ReportAllocs()
 var arr [100000]U3
 for i := 0; i < b.N; i++ {
  for j, v := range arr {
   arr[j].d = j
   _ = v
  }
 }
}
func BenchmarkForRangeLargeStructArrayU2(b *testing.B) {
 b.ReportAllocs()
 var arr [100000]U2
 for i := 0; i < b.N; i++ {
  for j, v := range arr {
   arr[j].d = j
   _ = v
  }
 }
}
func BenchmarkForRangeLargeStructArrayU1(b *testing.B) {
 b.ReportAllocs()
 var arr [100000]U1
 for i := 0; i < b.N; i++ {
  for j, v := range arr {
   arr[j].d = j
   _ = v
  }
 }
}
Copy after login

在这个例子中,我们定义了 5 种类型的结构体:U1~U5,它们的区别在于包含的 int 类型字段的数量。

性能测试结果如下

 $ go test -bench . forRange2_test.go
goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i5-8279U CPU @ 2.40GHz
BenchmarkClassicForLoopLargeStructArrayU5-8        44540             26227 ns/op               0 B/op          0 allocs/op
BenchmarkClassicForLoopLargeStructArrayU4-8        45906             26312 ns/op               0 B/op          0 allocs/op
BenchmarkClassicForLoopLargeStructArrayU3-8        43315             27400 ns/op               0 B/op          0 allocs/op
BenchmarkClassicForLoopLargeStructArrayU2-8        44605             26313 ns/op               0 B/op          0 allocs/op
BenchmarkClassicForLoopLargeStructArrayU1-8        45752             26110 ns/op               0 B/op          0 allocs/op
BenchmarkForRangeLargeStructArrayU5-8               3072            388651 ns/op               0 B/op          0 allocs/op
BenchmarkForRangeLargeStructArrayU4-8               4605            261329 ns/op               0 B/op          0 allocs/op
BenchmarkForRangeLargeStructArrayU3-8               5857            182565 ns/op               0 B/op          0 allocs/op
BenchmarkForRangeLargeStructArrayU2-8              10000            108391 ns/op               0 B/op          0 allocs/op
BenchmarkForRangeLargeStructArrayU1-8              36333             32346 ns/op               0 B/op          0 allocs/op
PASS
ok      command-line-arguments  16.160s
Copy after login

我们看到一个现象:不管是什么类型的结构体元素数组,经典的 for 循环遍历的性能比较一致,但是 for range 的遍历性能会随着结构字段数量的增加而降低。

带着疑惑,发现了一个与这个问题相关的 issue:cmd/compile: optimize large structs:https://github.com/golang/go/issues/24416。这个 issue 大致是说:如果一个结构体类型有超过一定数量的字段(或一些其他条件),就会将该类型视为 unSSAable。如果 SSA 不可行,那么就无法通过 SSA 优化,这也是造成上述基准测试结果的重要原因。

结论

对于遍历大数组而言, for 循环能比 for range 循环更高效与稳定,这一点在数组元素为结构体类型更加明显。

另外,由于在 Go 中切片的底层都是通过数组来存储数据,尽管有 for range 的副本复制问题,但是切片副本指向的底层数组与原切片是一致的。这意味着,当我们将数组通过切片代替后,不管是通过 for range 或者 for 循环均能得到一致的稳定的遍历性能。

The above is the detailed content of Handling large arrays in Go: use for range or for loop?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
How to send Go WebSocket messages? How to send Go WebSocket messages? Jun 03, 2024 pm 04:53 PM

In Go, WebSocket messages can be sent using the gorilla/websocket package. Specific steps: Establish a WebSocket connection. Send a text message: Call WriteMessage(websocket.TextMessage,[]byte("Message")). Send a binary message: call WriteMessage(websocket.BinaryMessage,[]byte{1,2,3}).

The difference between Golang and Go language The difference between Golang and Go language May 31, 2024 pm 08:10 PM

Go and the Go language are different entities with different characteristics. Go (also known as Golang) is known for its concurrency, fast compilation speed, memory management, and cross-platform advantages. Disadvantages of the Go language include a less rich ecosystem than other languages, a stricter syntax, and a lack of dynamic typing.

How to match timestamps using regular expressions in Go? How to match timestamps using regular expressions in Go? Jun 02, 2024 am 09:00 AM

In Go, you can use regular expressions to match timestamps: compile a regular expression string, such as the one used to match ISO8601 timestamps: ^\d{4}-\d{2}-\d{2}T \d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-][0-9]{2}:[0-9]{2})$ . Use the regexp.MatchString function to check if a string matches a regular expression.

How to avoid memory leaks in Golang technical performance optimization? How to avoid memory leaks in Golang technical performance optimization? Jun 04, 2024 pm 12:27 PM

Memory leaks can cause Go program memory to continuously increase by: closing resources that are no longer in use, such as files, network connections, and database connections. Use weak references to prevent memory leaks and target objects for garbage collection when they are no longer strongly referenced. Using go coroutine, the coroutine stack memory will be automatically released when exiting to avoid memory leaks.

Things to note when Golang functions receive map parameters Things to note when Golang functions receive map parameters Jun 04, 2024 am 10:31 AM

When passing a map to a function in Go, a copy will be created by default, and modifications to the copy will not affect the original map. If you need to modify the original map, you can pass it through a pointer. Empty maps need to be handled with care, because they are technically nil pointers, and passing an empty map to a function that expects a non-empty map will cause an error.

How to use Golang's error wrapper? How to use Golang's error wrapper? Jun 03, 2024 pm 04:08 PM

In Golang, error wrappers allow you to create new errors by appending contextual information to the original error. This can be used to unify the types of errors thrown by different libraries or components, simplifying debugging and error handling. The steps are as follows: Use the errors.Wrap function to wrap the original errors into new errors. The new error contains contextual information from the original error. Use fmt.Printf to output wrapped errors, providing more context and actionability. When handling different types of errors, use the errors.Wrap function to unify the error types.

How to create a prioritized Goroutine in Go? How to create a prioritized Goroutine in Go? Jun 04, 2024 pm 12:41 PM

There are two steps to creating a priority Goroutine in the Go language: registering a custom Goroutine creation function (step 1) and specifying a priority value (step 2). In this way, you can create Goroutines with different priorities, optimize resource allocation and improve execution efficiency.

How to use gomega for assertions in Golang unit tests? How to use gomega for assertions in Golang unit tests? Jun 05, 2024 pm 10:48 PM

How to use Gomega for assertions in Golang unit testing In Golang unit testing, Gomega is a popular and powerful assertion library that provides rich assertion methods so that developers can easily verify test results. Install Gomegagoget-ugithub.com/onsi/gomega Using Gomega for assertions Here are some common examples of using Gomega for assertions: 1. Equality assertion import "github.com/onsi/gomega" funcTest_MyFunction(t*testing.T){

See all articles