Java Reference
In-Depth Information
public static boolean isOdd(int i) {
return i % 2 != 0;
}
If you are using the isOdd method in a performance-critical setting, you would be better off using
the bitwise AND operator ( & ) in place of the remainder operator:
public static boolean isOdd(int i) {
return (i & 1) != 0;
}
The second version may run much faster than the first, depending on what platform and virtual
machine you are using, and is unlikely to run slower. As a general rule, the divide and remainder
operations are slow compared to other arithmetic and logical operations. It's a bad idea to
optimize prematurely , but in this case, the faster version is as clear as the original, so there is no
reason to prefer the original.
In summary, think about the signs of the operands and of the result whenever you use the remainder
operator. The behavior of this operator is obvious when its operands are nonnegative, but it isn't so
obvious when one or both operands are negative.
< Day Day Up >
 
 
Search WWH ::




Custom Search