Effective BigInteger in Java

We have a set of locations in our product where BigInteger is required, as the numbers can be quite long. However, in more than 90% of cases, they are actually not so long and can be easily arranged over time.

Looking at the implementation of BigInteger, it would be nice to spend time using BigInteger, where Long is enough.

Would it be prudent to create an interface that has functions like BigInteger (division, multiplication, etc.), and this will be implemented by the BigInteger child class and the class that wraps Long? Something like:

Interface: EfficientBigInteger Class 1: MyBigInteger extends BigInteger imlpements EfficientBigInteger Class 2: MyLong implements EfficientBigInteger (this will contain a Long, as we cannot extend the Long class) 

Perhaps we are in the wrong direction?

Thanks Yon

UPDATE: These objects (Long or BigInteger) are stored in memory for quite some time, since they help us identify the problematic behavior of the systems with which we interact. Therefore, a memory issue can be a problem. This is a problem that we are trying to avoid. The BigInteger class has several fields (signum, mag array, bitcount, etc. etc.), which are approximately twice as large as the class that encapsulates Long (taking into account the memory costs associated with the presence of the object in the first place ) This means that we double what we use.

+7
source share
2 answers

Do I need to do arithmetic on these values? Because if you do, then one that starts as long can become BigInteger, and it sounds like a pain: you have to precede every arithmetic operation with a test that MAX_LONG can pass. Well, I suppose you could mask all this in your wrapper class. How long does it take to check for overflow, compared with the time that the BigInteger class takes to loop through an array of 1 or 2 elements?

If you do not perform arithmetic, then saving using long will be minimal. What do you do with BigInteger, just read it and write it down? In this case, there is almost certainly no problem.

Personally, this is what I am tempted to do myself, I understand your thinking. But then I would step back and say: "Is performance really a problem? How much arithmetic are we doing? How much would we get a performance gain? Is it worth adding complexity to the program and possibly introducing errors?

If you have no reason to believe that performance is indeed a problem, and that this will be significant, I would not.

+6
source

I implemented just such a thing for the Cobol compiler around 1986. It did not matter for performance: the overhead of deciding whether it would fit in a long time, and then convert it to long, and then vice versa, equal to the time savings.

+4
source

All Articles