/** * no if statement in this method * use shift operators * if positive num : num >> 31 == 0 * if negative num : num >> 31 == -1 * ~0 = -1 (ffffffff) * ~-1 = 0 (0) */ publicstaticvoidsumAvoidBranchPrediction(int[] array, int arraySize) { longstart= System.nanoTime(); longsum=0;
for (inti=0; i < arraySize; ++i) { for (intj=0; j < arraySize; ++j) { sum += ~((array[j] - 128) >> 31) & array[j]; } } System.out.println(System.nanoTime() - start + " ns"); // _606_267_300 ns System.out.println("sum : " + sum); }