I have a range of objects that have a long
field whose value uniquely identifies a particular object across my entire system, much like a GUID. I have overriden
Java 8 adds Long.hashCode(long) to the JDK.
The following code could yield higher performance. This code reduces the calculation to 32-bit int
instead of computing with 64-bit long
. This can make a difference on 32-bit and smaller architectures. 32-bit processes on x86 machines could optimize this into a single instruction which simply XORs 2 registers.
return (int)(value ^ (value >>> 32));
As noted in other answers, this does not have a good avalanche effect and hence could lead to collisions. One could go with cryptographic hash functions to ensure high avalanche effect. However, there are other algorithms such as Murmur Hash (more information) which have very good avalanche effect but don't consume as much CPU time.