What is the effect of ordering if…else if statements by probability?

Specifically, if I have a series of if…else if statements, and I somehow know beforehand the relative probability that each statement will evaluate to true, how much difference in execution time does it make to sort them in order of probability? For example, should I prefer this: if (highly_likely) //do something else if (somewhat_likely) //do … Read more

Why is (a*b != 0) faster than (a != 0 && b != 0) in Java?

I’m writing some code in Java where, at some point, the flow of the program is determined by whether two int variables, “a” and “b”, are non-zero (note: a and b are never negative, and never within integer overflow range). I can evaluate it with if (a != 0 && b != 0) { /* … Read more

Why is processing a sorted array faster than processing an unsorted array?

Here is a piece of C++ code that shows some very peculiar behavior. For some strange reason, sorting the data (before the timed region) miraculously makes the loop almost six times faster. #include <algorithm> #include <ctime> #include <iostream> int main() { // Generate data const unsigned arraySize = 32768; int data[arraySize]; for (unsigned c = … Read more