Add a fast track to d.Cmp(d2) when d.exp == d2.exp

This makes a noticeable difference when one is sorting a large slice
of decimals when most of them have the same precision, as it is saving
a lot of calls to rescale().
This commit is contained in:
Piotr 2015-12-11 23:54:57 +01:00
parent 9995dc92ee
commit cb949cead4
2 changed files with 24 additions and 0 deletions

View file

@ -294,6 +294,13 @@ func (d Decimal) Div(d2 Decimal) Decimal {
// +1 if d > d2
//
func (d Decimal) Cmp(d2 Decimal) int {
d.ensureInitialized()
d2.ensureInitialized()
if d.exp == d2.exp {
return d.value.Cmp(d2.value)
}
baseExp := min(d.exp, d2.exp)
rd := d.rescale(baseExp)
rd2 := d2.rescale(baseExp)

View file

@ -4,6 +4,7 @@ import (
"encoding/json"
"encoding/xml"
"math"
"sort"
"strconv"
"strings"
"testing"
@ -895,3 +896,19 @@ func didPanic(f func()) bool {
return ret
}
type DecimalSlice []Decimal
func (p DecimalSlice) Len() int { return len(p) }
func (p DecimalSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p DecimalSlice) Less(i, j int) bool { return p[i].Cmp(p[j]) < 0 }
func Benchmark_Cmp(b *testing.B) {
decimals := DecimalSlice([]Decimal{})
for i := 0; i < 1000000; i++ {
decimals = append(decimals, New(int64(i), 0))
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
sort.Sort(decimals)
}
}