Over the new year holiday I wrote a rational number in Java just for lulz. I was looking at it the other night and thought of a way to make the code for rounding to an integer more elegant using a
There’s a bit of code that’s computationally expensive that I don’t need to do unless the RoundingMode is one of HALF_UP, HALF_DOWN or HALF_EVEN; so I’m wondering whether
Another important question: do I really care, or am I just engaging in premature optimization? 😎
Here’s a screenshot of a bit of WinDiff output to show what I’m thinking of:
Not a Guru by any means, but the docs https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html claim that it is implemented as a bit vector, so it should be fast enough.
But as with all things Java, it is safest to measure the actual performance, but either way this will just be a micro-optimization compared to making sure the code only does that type of rounding when necessary.
I’m only having fun here, so I don’t plan on carefully measuring the performance. 😎 I’ve got the three-comparison code now; but I might change that to the EnumSet version just because it’s COOL and it gives me something to do. 😎
The only places where my code uses one of the HALF_* rounding modes are three methods that mimic the java.lang.Math methods, round(), rint() and IEEEremainder(); and users must explicitly call those.
OK, that was easy. If anybody cares, I’ve got user documentation for the latest version at https://www.cstdbill.com/lulz/rational.java.html; and at the end of the introduction, there’s a link to a ZIP file that contains the code along with the documentation and code for the version that just uses longs for the numerator and denominator.
Explicit ifs will be a tiny bit better (easier for the compiler to be smart at optimising code) but the difference should be trivial.
(Guru no, 23 years of Java yes)