Code Pretty Print Script

Sunday, November 17, 2013

Even-Odd Optimization

When you want to test whether something is even or odd, don't use the expensive modulo operation like this -
      
    for (int i = 0; i < 100; ++i) {
      if (i % 2 == 0) {
        System.out.println("i = " + i + " is even.");
      } else {
        System.out.println("i = " + i + " is odd.");
      }
    }
You should probably use this instead -

    for (int i = 0; i < 100; ++i) {
      if ((i & 1) == 0) {
        System.out.println("i = " + i + " is even.");
      } else {
        System.out.println("i = " + i + " is odd.");
      }
    }