Last active
August 10, 2024 15:01
-
-
Save gnsalok/981da1481f47a7c4668a43db546050b5 to your computer and use it in GitHub Desktop.
Benchmark value stored as interface vs struct
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 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=. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result :