Reputation: 477
I am implementation a distributed key-value store in Java. I need to save a timestamp for each key. Since I want to have a large of number of keys in the system, I decided to use BigInteger
instead of long
, but I am concerned about its efficiency.
Note that I don't have any multiplication, I only used addition
and comparTo
.
So do you think the BigInteger
is significantly less efficient than long
?
It is the first time that I am trying BigInteger
, is there any other concern comparing to long
?
Upvotes: 3
Views: 12570
Reputation: 340340
Instant
If you want a timestamp, we already have a class for that: Instant
represents a moment on the timeline in UTC with a resolution up to nanoseconds.
Instant instant = Instant.now() ;
In Java 8 the current moment is captured with a resolution up to milliseconds. In Java 9 a new implementation of Clock
captures the current moment up to the full nanosecond resolution, depending on your computer clock hardware.
But if you want to identify objects across distributed systems, use the type invented for just that purpose: Universally Unique Identifier (UUID). This type is defined in official standards. Made of a 128-bit value, basically an unimaginably large number, but certain bits have certain meanings.
For human reading, a hex string is generated in a canonical format.
Java includes a UUID
class to represent such values. Stored internally as a pair of 64-bit long
numbers in the OpenJDK implementation as I recall.
UUID uuid = UUID.randomUUID() ;
String hex = uuid.toString() ;
BigInteger
> long
And to answer your direct issue, BigInteger
is designed to represent ginormous numbers, not designed for efficiency. A long
primitive (64-bit number) uses much less memory since it lacks the overhead of a class & object and the machinery for representing and operating on ginormous numbers that may be much larger than fit into CPU registers. And operations on a long
execute much faster.
So, when you do not need the features of BigInteger
, stick with long
primitive.
Upvotes: 4
Reputation: 28846
No. BigInteger
needs more memory than a long
, and because it is not a primitive type, it is also slower. I would only use it when you need more digits than a long can provide.
For your purposes, a long
should be sufficient (and more efficient), as far as I can tell.
Upvotes: 5