Last active
December 17, 2019 22:31
-
-
Save aboglioli/b34c7abac6efd0da38e1e82228f42ad5 to your computer and use it in GitHub Desktop.
Go: function declaration vs var (benchmark)
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" | |
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) | |
} | |
} |
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
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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If function is declared outside using
var
it takes more time.