Here is an example of what probably ends up being a pointless optimization, but it
is a completely different approach to the other posted solutions.
Generally integer addition and subtraction take fewer
cpu cycles than multiplication and division. With that in mind
you might try the following:
int fizzcnt = 0;
int buzzcnt = 0;
String msg;
for(int num = 1; num <= 100; num++) {
fizzcnt++;
buzzcnt++;
if (fizzcnt == 3) {
msg = "Fizz";
fizzcnt = 0;
}//this bracket was missing
else {
msg = "";
}
if (buzzcnt == 5) {
msg = msg.concat("Buzz");
buzzcnt = 0;
}
System.out.format("%s %d%n", msg, num);
}
Managed to write the whole thing with 1 loop, 2 if statements and no multiplication/division/modulus
calculations. This should be more efficient. Maybe not. Notice the output message is created using String and concat.
these little guys probably suck up a lot more cycles than were gained through elimination of the other statements. You
would have to profile the code to really know.
The lesson here is it is probably better to work on readability and logical simplicity than it is
to worry about efficiency - unless performance becomes a real concern. When efficiency does become a concern be prepared to spend a lot of time using a profiler and running
benchmarks to verify that what you are doing is truly an improvement.
System.out.println
. It also has only 100 iterations, so JVM startup is more expensive than your code. Are you sue you want to increase efficiency? Unless you know (usually because your profiled it) that this code is too slow, I'd focus on readability over performance. \$\endgroup\$