text
In go language development, slice is one of the commonly used data types. It is also because of its flexibility and I rarely use arrays. Of course, I also know some of its features, but I don’t really verify it, because most usage scenarios do not need to be too strict with code. However, if the encapsulation is provided as a package for other logic, I think I still have to care about these things. After all, when used as a public package, it proves the frequency of use. So some things should be recorded. Last week, I have nothing to do and make a record today
Various scenario codes
In fact, we all know that the underlying logic of slice is a dynamic array, and the creation method is slightly different. The creation of slice can also be the simplest make, which can satisfy our use, and it can directly specify its cap capacity. The best way is to declare its capacity while directly allocating its memory. The code for various scenarios is as follows, and the iterator has been tested 1000 times as an example:
/* Package main @Time : 2022/11/25 17:47 @Author : ckx0709 @Remark : */ package main // SliceUseSimple simple initializationfunc SliceUseSimple() []int { is := make([]int, 0) for i := 0; i < 1000; i++ { is = append(is, i) } return is } // SliceUseInitCap Initialization Capacityfunc SliceUseInitCap() []int { is := make([]int, 0, 1000) for i := 0; i < 1000; i++ { is = append(is, i) } return is } // SliceUseInitFull Initialize capacity & allocate memoryfunc SliceUseInitFull() []int { is := make([]int, 1000, 1000) for i := 0; i < 1000; i++ { is[i] = i } return is } // ArrayUse arrayfunc ArrayUse() []int { var is [1000]int for i := 0; i < 1000; i++ { is[i] = i } return is[:] }
Testing with benchmark
$ go test -benchmem -bench=Benchmark* goos: windows goarch: amd64 pkg: go_iteration/other/temp cpu: Intel(R) Core(TM) i5-9400 CPU @ 2.90GHz BenchmarkSliceUseSimple-6 348466 3501 ns/op 25208 B/op 12 allocs/op BenchmarkSliceUseInitCap-6 2190738 548.7 ns/op 0 B/op 0 allocs/op BenchmarkSliceUseInitFull-6 4408171 261.4 ns/op 0 B/op 0 allocs/op BenchmarkArrayUse-6 4483910 262.1 ns/op 0 B/op 0 allocs/op PASS ok go_iteration/other/temp 6.067s
After running 3 times, the value deviation is not large, so there is no need to post it every time. This shows that when we use the simplest declaration method & declaration, we allocate everything first. The performance difference is more than ten times, and the simplest declaration method occupies memory & allocates memory many times. The second type only proves that there is a double difference in performance compared to the good capacity & full declaration, and the efficiency of the full declaration & array is basically the same.
The above is a detailed explanation of the performance and arrays of different initialization methods of go slice. For more information on the performance comparison of go slice initialization methods, please pay attention to my other related articles!