Wondering why does Java use << 1
extensively to double an Integer's value?
e.g. in HashMap
there's
// HashMap#resize
newThr = oldThr << 1; // double threshold
I believe the performance between << 1
and * 2
is similar?
Although you can argue that performace between the binary shift vs arithmentic multiplication using operator are almost same in modern CPUs , bitwise operations are absolutely essential when programming hardware registers in embedded systems.In general, bitwise operations come into play a lot when you need to encode or decode data in a compact and fast way.These types of operations are often used on embedded systems where memory or CPU power is limited.For example, to save space you may store multiple variables in a single 8-bit int variable by using each bit as a boolean value. In this case, you need a way to quickly set a particular bit or retrieve its value. Many embedded systems have a storage capacity of 64, 128 or 256 BYTES (those are bytes, not kilobytes or megabytes). A byte is typically used in this environment to store multiple data items, boolean flags, or anything else that can be set or read using bit operations.
Bit-wise operators are also common in video and audio codecs for similar reasons embedded electronics uses them; if you want a super-efficient video codec, you can have five flags and an eleven-bit timer in half an integer. Bit-wise operators now emphasize readability more than ever.
map size MUST be a power of two
. But that doesn't quite answer my question here I think?<< 1
and* 2
will pretty much behave the same on any modern CPU (i.e. what your computer likely uses), this is not necessarily the case for emebedded hardware and the like - they might behave differently and the performance impact could be quite heavy. Since this is a general purpose implementation and Java is also meant to be used on emebedded devices, it has to be "as fast as possible". Even if that sacrifices readability. There are also other examples of such tradeoffs, e.g.foo[i++]
instead of having it in 2 lines.