Reputation: 712
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?
Upvotes: 0
Views: 208
Reputation: 590
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.
Upvotes: 2