Last active
October 6, 2023 02:59
-
-
Save Maki-Daisuke/705b36783b267f932fd6ad09a368200b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"testing" | |
) | |
const ARRAY_SIZE = 100000 | |
func mkArray() []int { | |
arr := make([]int, ARRAY_SIZE) | |
for i := 0; i < ARRAY_SIZE; i++ { | |
arr[i] = i | |
} | |
return arr | |
} | |
func BenchmarkUseAppend(b *testing.B) { | |
arrays := make([][]int, b.N) | |
for i := 0; i < b.N; i++ { | |
arrays[i] = mkArray() | |
} | |
b.ResetTimer() | |
idx := 0 | |
for i := 0; i < b.N; i++ { | |
arr := arrays[i] | |
for len(arr) > 0 { | |
arr = append(arr[:idx], arr[idx+1:]...) | |
} | |
} | |
} | |
func BenchmarkUseManualCopy(b *testing.B) { | |
arrays := make([][]int, b.N) | |
for i := 0; i < b.N; i++ { | |
arrays[i] = mkArray() | |
} | |
b.ResetTimer() | |
idx := 0 | |
for i := 0; i < b.N; i++ { | |
arr := arrays[i] | |
for len(arr) > 0 { | |
for j := idx; j < len(arr)-1; j++ { | |
arr[j] = arr[j+1] | |
} | |
arr = arr[:len(arr)-1] | |
} | |
} | |
} | |
func BenchmarkUseCopy(b *testing.B) { | |
arrays := make([][]int, b.N) | |
for i := 0; i < b.N; i++ { | |
arrays[i] = mkArray() | |
} | |
b.ResetTimer() | |
idx := 0 | |
for i := 0; i < b.N; i++ { | |
arr := arrays[i] | |
for len(arr) > 0 { | |
copy(arr[idx:], arr[idx+1:]) | |
arr = arr[:len(arr)-1] | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
❯ go test -bench . -benchmem | |
goos: windows | |
goarch: amd64 | |
pkg: gist.github.com/Maki-Daisuke/go-bench-array-delete | |
cpu: 13th Gen Intel(R) Core(TM) i7-13700F | |
BenchmarkUseAppend-24 3 492529833 ns/op 0 B/op 0 allocs/op | |
BenchmarkUseManualCopy-24 1 1230478800 ns/op 0 B/op 0 allocs/op | |
BenchmarkUseCopy-24 3 489893567 ns/op 0 B/op 0 allocs/op | |
PASS | |
ok gist.github.com/Maki-Daisuke/go-bench-array-delete 7.988s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment