Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reason for BigInt implementation #311

Open
abonec opened this issue Feb 23, 2023 · 0 comments
Open

Reason for BigInt implementation #311

abonec opened this issue Feb 23, 2023 · 0 comments

Comments

@abonec
Copy link

abonec commented Feb 23, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant