Question #1
In Java, is shifting multiple times more expensive than using a single statement to shift the by the same number?
For example, is
int x = 5;
x = x << 16;
Faster than
int x = 5;
for (int i=0; i<16; ++i) {
x = x << 1;
}
Further, what about
int x = 5;
for (int i=0; i<16; ++i) {
x = x*2;
}
Edit: What is the precise performance of “x << 16”? Is it the same speed as “x << 1”?
Question #2
Is there a resource online that I can utilize to determine various bitwise operation performances in Java, so that I do not have to waste the time of StackOverflow users? 🙂
In terms of basic logic, a single shift would give much greater performance.
When using the
for loopversion, for every iteration of the loop, the loop’s terminating condition is checked,iis incremented, a bitwise operation is carried out and an assignment is made tox.When using a single shift, a single bitwise operation is carried out and an assignment is made to
x.And as others have said, this really does seem like premature optimisation.
For the sake of answering your question though, logically, the first example is faster than the others.
That said, depending on the language and compiler, it is possible that the compiler would see that your
for loopalways runs 16 times and then proceeds to optimise your code, changing it tox << 16. If this is the case, you would see no difference between each code example you gave.