Skip to content

Instantly share code, notes, and snippets.

@Ja7ad
Last active April 30, 2023 05:50
Show Gist options
  • Save Ja7ad/f51d01684eca78dad5b69046ad3a356b to your computer and use it in GitHub Desktop.
Save Ja7ad/f51d01684eca78dad5b69046ad3a356b to your computer and use it in GitHub Desktop.
benchmark clear feature in go1.21
package main
import (
"testing"
"time"
)
func BenchmarkClearMapWithDelete(b *testing.B) {
b.ReportAllocs()
test := createMap(100000)
for i := 0; i < b.N; i++ {
for k := range test {
delete(test, k)
}
}
}
func BenchmarkClearMapWithClear(b *testing.B) {
b.ReportAllocs()
test := createMap(100000)
for i := 0; i < b.N; i++ {
clear(test)
}
}
func BenchmarkClearSliceWithoutClear(b *testing.B) {
b.ReportAllocs()
test := createSlice(100000)
for i := 0; i < b.N; i++ {
for k := range test {
deleteSliceElement(test, k)
}
}
}
func BenchmarkClearSliceWithClear(b *testing.B) {
b.ReportAllocs()
test := createSlice(100000)
for i := 0; i < b.N; i++ {
clear(test)
}
}
//go:noinline
func deleteSliceElement(slice []int64, element int) []int64 {
slice[element] = slice[len(slice)-1]
slice = slice[:len(slice)-1]
return slice
}
func createMap(n int) map[int]int64 {
data := make(map[int]int64)
for i := 0; i < n; i++ {
data[i] = time.Now().Unix()
}
return data
}
//go:noinline
func createSlice(n int) []int64 {
data := make([]int64, 0)
for i := 0; i < n; i++ {
data = append(data, time.Now().Unix())
}
return data
}
@Ja7ad
Copy link
Author

Ja7ad commented Apr 30, 2023

Result:

goos: linux
goarch: amd64
cpu: AMD Ryzen 3 PRO 2300U w/ Radeon Vega Mobile Gfx
BenchmarkClearMapWithDelete
BenchmarkClearMapWithDelete-4       	415942981	         2.488 ns/op	       0 B/op	       0 allocs/op
BenchmarkClearMapWithClear
BenchmarkClearMapWithClear-4        	385395132	         2.602 ns/op	       0 B/op	       0 allocs/op
BenchmarkClearSliceWithoutClear
BenchmarkClearSliceWithoutClear-4   	    4663	    281625 ns/op	     879 B/op	       0 allocs/op
BenchmarkClearSliceWithClear
BenchmarkClearSliceWithClear-4      	   76146	     16391 ns/op	      53 B/op	       0 allocs/op
PASS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment