In the blog I wrote, this is considered to be relatively high in participation, so it is necessary to write the program more easily.
My computer configuration:
☁ bechmark system_profiler SPHardwareDataType
Hardware:Hardware Overview:
Model Name: MacBook Pro
Model Identifier: MacBookPro14,1
Processor Name: Dual-Core Intel Core i5
Processor Speed: 2.3 GHz
Number of Processors: 1
Total Number of Cores: 2
L2 Cache (per Core): 256 KB
L3 Cache: 4 MB
Hyper-Threading Technology: Enabled
Memory: 8 GB
Boot ROM Version: 428.0.0.0.0
SMC Version (system): 2.43f10
Directly upload the code:
package bechmark import ( "testing" ) var ( // Original slice origin = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} // Elements that need to be deleted targetEle = 6 ) // The first typefunc BenchmarkMake(t *) { () for i := 0; i < ; i++ { target := make([]int, 0, len(origin)) for _, item := range origin { if item != targetEle { target = append(target, item) } } } } // The second typefunc BenchmarkReuse(t *) { () for i := 0; i < ; i++ { target := origin[:0] for _, item := range origin { if item != targetEle { target = append(target, item) } } } } // The third typefunc BenchmarkEditOne(t *) { () for i := 0; i < ; i++ { for i := 0; i < len(origin); i++ { if origin[i] == targetEle { origin = append(origin[:i], origin[i+1:]...) i-- // maintain the correct index } } } }
Benchmark results:
☁ bechmark go test -v -bench=. -benchtime=3s -benchmem
goos: darwin
goarch: amd64
pkg: test/bechmark
BenchmarkMake-4 95345845 35.8 ns/op 80 B/op 1 allocs/op
BenchmarkReuse-4 255912920 14.4 ns/op 0 B/op 0 allocs/op
BenchmarkEditOne-4 473434452 7.56 ns/op 0 B/op 0 allocs/op
PASS
ok test/bechmark 12.915s
explain:
- Except for the first method, the other methods have modified the original data;
- The first method is suitable for use without polluting the original slice data. This method is also relatively simple. Most people who learn golang can think of it. However, the performance is slightly worse and there is memory allocation, but it also depends on business needs;
- The second method is more clever. I also saw a master who created a slice, but shared the underlying array of the original slice; this way, there is no need to allocate additional memory space and directly modify it on the original data.
- The third method will also modify the underlying array, and the idea is exactly the opposite of the first two. If you find an element that needs to be removed, move the subsequent element forward to cover the position of the element.
Summarize
This is the article about the performance comparison of slice deletion elements in Golang. For more related contents of Golang slice deletion elements, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!