Skip to content

Instantly share code, notes, and snippets.

@gnsalok
Last active August 10, 2024 15:01
Show Gist options
  • Save gnsalok/981da1481f47a7c4668a43db546050b5 to your computer and use it in GitHub Desktop.
Save gnsalok/981da1481f47a7c4668a43db546050b5 to your computer and use it in GitHub Desktop.
Benchmark value stored as interface vs struct
package benchamarking
import (
"testing"
)
type MyStruct struct {
Value int
}
func (ms MyStruct) GetValue() int {
return ms.Value
}
type MyInterface interface {
GetValue() int
}
func BenchmarkInterface(b *testing.B) {
var data []MyInterface
for i := 0; i < 1000000; i++ {
data = append(data, MyStruct{Value: i})
}
for i := 0; i < b.N; i++ {
for _, v := range data {
_ = v.GetValue()
}
}
}
func BenchmarkConcrete(b *testing.B) {
var data []MyStruct
for i := 0; i < 1000000; i++ {
data = append(data, MyStruct{Value: i})
}
for i := 0; i < b.N; i++ {
for _, v := range data {
_ = v.Value
}
}
}
/* -- To run the test
# go test -bench=.
*/
@gnsalok
Copy link
Author

gnsalok commented Aug 10, 2024

Result :

image

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