Created
August 10, 2017 00:51
-
-
Save odeke-em/27fbbdb69eb6e56e213bdaddebb369b6 to your computer and use it in GitHub Desktop.
comparing var big.NewInt(0) vs allocating big.NewInt(0) everytime
This file contains hidden or 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 ( | |
"math/big" | |
"testing" | |
) | |
var bns = []*big.Int{ | |
big.NewInt(0), | |
big.NewInt(10), | |
big.NewInt(10000), | |
} | |
func BenchmarkRawAllocCmp(b *testing.B) { | |
var recv bool | |
for i := 0; i < b.N; i++ { | |
for _, bn := range bns { | |
recv = cmpRawAlloc(bn) | |
} | |
} | |
b.ReportAllocs() | |
if recv { | |
recv = false | |
} | |
} | |
func BenchmarkVarCmp(b *testing.B) { | |
var recv bool | |
for i := 0; i < b.N; i++ { | |
for _, bn := range bns { | |
recv = cmpVar(bn) | |
} | |
} | |
b.ReportAllocs() | |
if recv { | |
recv = false | |
} | |
} | |
func cmpRawAlloc(bn *big.Int) bool { | |
return bn.Cmp(big.NewInt(0)) == 0 | |
} | |
var bigZero = big.NewInt(0) | |
func cmpVar(bn *big.Int) bool { | |
return bn.Cmp(bigZero) == 0 | |
} |
This file contains hidden or 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
$ go test -v -run=^$ -bench=. | |
goos: darwin | |
goarch: amd64 | |
BenchmarkRawAllocCmp-4 10000000 168 ns/op 96 B/op 3 allocs/op | |
BenchmarkVarCmp-4 50000000 29.1 ns/op 0 B/op 0 allocs/op | |
PASS |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment