I was able to convert the fixed package to use generics to allow a variable number of decimal places.
benchmark old ns/op new ns/op delta
BenchmarkAddFixed-8 0.98 0.96 -1.66%
BenchmarkMulFixed-8 5.44 22.8 +318.15%
BenchmarkDivFixed-8 3.71 12.9 +246.97%
BenchmarkCmpFixed-8 0.26 0.54 +108.74%
BenchmarkStringFixed-8 51.8 55.2 +6.44%
BenchmarkStringNFixed-8 51.9 55.8 +7.51%
I assume the decrease in performance is due to the methods calls to determine the number of places, scaling factor etc.
Even though the method calls return constants, it doesn’t seem the compiler is inlining the constant. I suspect because I needed to declare the struct at
type FixedN[T Places] struct {
places T
fp int64
}
and it is determining that places is not a constant.
I think if the original generics design was implemented, so:
type FixedN[T Places] struct {
T
fp int64
}
then it would be able to determine that the implementation is constant for the type.
Although to be honest, I am uncertain how the struct size is 8 in the first case - because then the compiler must be able to determine that places is a constant.
Thoughts?