Created
August 27, 2024 17:59
-
-
Save Egor3f/bbf061a8467c9d71fdcf3d1a5d1d0f96 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 sparse_gogo | |
import ( | |
"fmt" | |
"strconv" | |
"testing" | |
) | |
const MIN_SIZE = 4 | |
const MAX_SIZE = 20 | |
const STEP = 2 | |
func createMap(size int) map[int]string { | |
m := make(map[int]string, size) | |
for i := 0; i < size; i++ { | |
m[i] = strconv.Itoa(i) | |
} | |
return m | |
} | |
func BenchmarkMapCreate(b *testing.B) { | |
for size := MIN_SIZE; size <= MAX_SIZE; size += STEP { | |
b.Run(fmt.Sprintf("Create map with size = %d", size), func(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
createMap(size) | |
} | |
}) | |
} | |
} | |
func BenchmarkMapAccess(b *testing.B) { | |
for size := MIN_SIZE; size <= MAX_SIZE; size += STEP { | |
m := createMap(size) | |
for _, idx := range []int{0, size / 2, size - 1} { | |
b.Run(fmt.Sprintf("Access map size=%d, index=%d", size, idx), func(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
v, ok := m[idx] | |
_, _ = v, ok | |
} | |
}) | |
} | |
} | |
} | |
type entry struct { | |
idx int | |
val string | |
} | |
func createSlice(size int) []entry { | |
slc := make([]entry, size) | |
for i := 0; i < size; i++ { | |
slc[i] = entry{i, strconv.Itoa(i)} | |
} | |
return slc | |
} | |
func BenchmarkSliceCreate(b *testing.B) { | |
for size := MIN_SIZE; size <= MAX_SIZE; size += STEP { | |
b.Run(fmt.Sprintf("Create slice size=%d", size), func(b *testing.B) { | |
createSlice(size) | |
}) | |
} | |
} | |
func BenchmarkSliceAccess(b *testing.B) { | |
for size := MIN_SIZE; size <= MAX_SIZE; size += STEP { | |
slc := createSlice(size) | |
for _, idx := range []int{0, size / 2, size - 1} { | |
b.Run(fmt.Sprintf("Access slice size=%d, index %d", size, idx), func(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
var v string | |
for _, ent := range slc { | |
if ent.idx == idx { | |
v = ent.val | |
break | |
} | |
} | |
_ = v | |
} | |
}) | |
} | |
} | |
} |
Author
Egor3f
commented
Aug 27, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment