简体   繁体   中英

Is BigInteger efficient compared to long?

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 ?

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.

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 .

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.

UUID

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM