Last active
April 30, 2023 05:50
-
-
Save Ja7ad/f51d01684eca78dad5b69046ad3a356b to your computer and use it in GitHub Desktop.
benchmark clear feature in go1.21
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" | |
"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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: