Skip to main content

Optimize modulo statement

2 replies [Last post]
rinok
Offline
Joined: 2008-05-24
Points: 0

Essentially the next two code snippets have the same purpose (counting odd), but the second one appears to be much faster at run-time. Would it be a good idea to optimize this compile time? Many programs are written using the if (x % 2 == 0) syntax. Might not be a big issue, but still.....

public static void main(String[] args) {
int count = 0;
for (int x = 0; x < Integer.MAX_VALUE; x++) {
if (x % 2 == 0)
count++;
}
System.out.print(count);
}

public static void main(String[] args) {
int count = 0;
int mask = Integer.MAX_VALUE - 1;
for (int x = 0; x < Integer.MAX_VALUE; x++) {
if ((mask | x) == Integer.MAX_VALUE)
count++;
}
System.out.print(count);
}

System Specs:
Product Version: NetBeans IDE 6.1 (Build 200804211638)
Java: 1.6.0_06; Java HotSpot(TM) Client VM 10.0-b22
System: Linux version 2.6.24-16-generic running on i386; UTF-8; en_US (nb)

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
sjasja
Offline
Joined: 2004-08-15
Points: 0

The two if() statements don't do quite the same thing as negative values will behave differently.

When microbenchmarking, put the tested code in a separate function. Then call that function five or ten times from main(), measuring the time of each call. Ignore the first few timings. Otherwise you run the risk of measuring Hotspot compilation time rather than run time.

When you have a CPU intensive program, use "java -server" to get the optimizing compiler. With -server and the above mentioned change I get almost the same timings from both programs.

rinok
Offline
Joined: 2008-05-24
Points: 0

Thanks for the comment. I fixed the bitmask issue to work with negative numbers as well. I disagree on the benchmarking and the "-server" feauture. I'm suggesting a compile time optimization.

public static void main(String[] args) {
long count = 0;
int mask = 1;
for (int x = Integer.MIN_VALUE; x < Integer.MAX_VALUE; x++) {
if ((mask & x) == 0)
count++;
}
System.out.print(count);
}