Skip to content

Instantly share code, notes, and snippets.

@odeke-em
Created August 10, 2017 00:51
Show Gist options
  • Save odeke-em/27fbbdb69eb6e56e213bdaddebb369b6 to your computer and use it in GitHub Desktop.
Save odeke-em/27fbbdb69eb6e56e213bdaddebb369b6 to your computer and use it in GitHub Desktop.
comparing var big.NewInt(0) vs allocating big.NewInt(0) everytime
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
}
$ 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