Skip to content

Instantly share code, notes, and snippets.

@aboglioli
Last active December 17, 2019 22:31
Show Gist options
  • Save aboglioli/b34c7abac6efd0da38e1e82228f42ad5 to your computer and use it in GitHub Desktop.
Save aboglioli/b34c7abac6efd0da38e1e82228f42ad5 to your computer and use it in GitHub Desktop.
Go: function declaration vs var (benchmark)
package main
import "testing"
func sum1(a, b int) int {
return a + b
}
func BenchmarkDefaultDeclaration(b *testing.B) {
for i := 0; i < b.N; i++ {
sum1(i, i)
}
}
func BenchmarkVarDeclaration1(b *testing.B) {
for i := 0; i < b.N; i++ {
var sum2 = func(a, b int) int {
return a + b
}
sum2(i, i)
}
}
func BenchmarkVarDeclaration2(b *testing.B) {
var sum3 = func(a, b int) int {
return a + b
}
for i := 0; i < b.N; i++ {
sum3(i, i)
}
}
var sum4 = func(a, b int) int {
return a + b
}
func BenchmarkVarDeclaration3(b *testing.B) {
for i := 0; i < b.N; i++ {
sum4(i, i)
}
}
goos: linux
goarch: amd64
BenchmarkDefaultDeclaration-8 1000000000 0.258 ns/op 0 B/op 0 allocs/op
BenchmarkVarDeclaration1-8 1000000000 0.256 ns/op 0 B/op 0 allocs/op
BenchmarkVarDeclaration2-8 1000000000 0.259 ns/op 0 B/op 0 allocs/op
BenchmarkVarDeclaration3-8 706787652 1.71 ns/op 0 B/op 0 allocs/op
PASS
ok _/home/kiriost/dev/tmp 2.237s
Success: Benchmarks passed.
@aboglioli
Copy link
Author

If function is declared outside using var it takes more time.

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