Double vs long serialization in Java
I can store a number as long and double in HBase They all occupy 8 bytes in Java
The advantage of using double is that it provides a wider range for storing integers
But I think long's range is enough for me to use
Does anyone have any ideas about the serialization and deserialization performance of long vs dobule? I'm interested in comparing them
thank you.
Solution
If you want to store integers, use long Your statement that "the advantage of using double is that it provides a wider range for storing integers" is incorrect Both are 64 bits long, but some bits must be used as an index, leaving fewer bits to represent the amplitude You can store larger numbers in a double, but you lose precision
In other words, for a number greater than an upper limit, you can no longer store adjacent "integers"... Given an integer value higher than this threshold, the possible double of "next" will be more than 1 greater than the previous number
for example
public class Test1 { public static void main(String[] args) throws Exception { long long1 = Long.MAX_VALUE - 100L; double dbl1 = long1; long long2 = long1+1; double dbl2 = dbl1+1; double dbl3 = dbl2+Math.ulp(dbl2); System.out.printf("%d %d\n%f %f %f",long1,long2,dbl1,dbl2,dbl3); } }
This output:
9223372036854775707 9223372036854775708 9223372036854776000.000000 9223372036854776000.000000 9223372036854778000.000000
be careful
> Long. MAX_ The double representation of value-100 is not equal to the original value > in long MAX_ Adding 1 to the double representation of value-100 is invalid > at this amplitude, the difference between one double and the next possible double value is 2000
Another argument is that long has less than 19 bit precision, while double has only 16 bit precision Double can store numbers larger than 16 bits, but at the cost of truncation / rounding with low numbers
If you need more than 19 digit precision, you must use BigInteger, and performance is expected to degrade