decimal icon indicating copy to clipboard operation
decimal copied to clipboard

Reason for BigInt implementation

Open abonec opened this issue 2 years ago • 0 comments

I'm curious why BigInt method uses string representation:

// BigInt returns integer component of the decimal as a BigInt.
func (d Decimal) BigInt() *big.Int {
	scaledD := d.rescale(0)
	i := &big.Int{}
	i.SetString(scaledD.String(), 10)
	return i
}

Seems that a return scaled to 0 coefficient would be enough:

// BigInt returns integer component of the decimal as a BigInt.
func (d Decimal) BigInt() *big.Int {
	return d.rescale(0).Coefficient()
}

Your tests are fine with that and benchmarks state about 2x performance and less allocs

func BenchmarkDecimal_BigInt(b *testing.B) {
	b.ResetTimer()

	d := RequireFromString("30.412346346346")
	b.ReportAllocs()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_ = d.BigInt()
	}
}
BenchmarkDecimal_BigInt-10                              	 3174534	       404.9 ns/op	     296 B/op	      15 allocs/op
BenchmarkDecimal_BigIntCoef-10                          	 5891038	       202.8 ns/op	     200 B/op	       9 allocs/op

Performance for this method is crucial for our application, so it would be nice to grasp why implementations through string representation. That answer will help me realize whether I can use it in my code or even send you a patch.

abonec avatar Feb 23 '23 10:02 abonec