- Feb 8, 2004
- 12,604
- 15
- 81
So I made a fizzbuzz program (yeah go me!) because it dawned on me ive never actually done that. I then made a modified version which in my mind should have been a bit faster but it wasent. fizzBuzz1 is the modified version, fizzBuzz2 is the original one I made.
After 1000 runs the average execution time of fizzBuzz1 was 1712
After 1000 runs the average execution time of fizzBuzz1 was 1646
Why is fizzBuzz2 faster? It does between 2 and 3 modulus calculations per run, fizzBuzz1 only ever does 2 calculations. I thought checking a stored boolean was faster than doing a calculation? What gives?
After 1000 runs the average execution time of fizzBuzz1 was 1712
Code:
public static long fizzBuzz1()
{
int maxNumber = 100000;
boolean fizzModulus;
boolean buzzModulus;
long startTime = System.currentTimeMillis();
long endTime;
long executionTime;
for (int count = 0; count <= maxNumber; count++)
{
//here we calculate if the number is fizz or buzz or both
fizzModulus = count % 3 == 0;
buzzModulus = count % 5 == 0;
//we then use the results to print out the appropriate text
if (fizzModulus && buzzModulus)
{
System.out.println("fizz buzz");
}
else
{
if (fizzModulus)
{
System.out.println("fizz");
}
else
{
if (buzzModulus)
{
System.out.println("buzz");
}
else
{
System.out.println(count);
}
}
}
}
endTime = System.currentTimeMillis();
executionTime = endTime - startTime;
System.out.println("Execution time: " + executionTime);
return executionTime;
}
After 1000 runs the average execution time of fizzBuzz1 was 1646
Code:
public static long fizzBuzz2()
{
int maxNumber = 100000;
long startTime = System.currentTimeMillis();
long endTime;
long executionTime;
for (int count = 0; count <= maxNumber; count++)
{
if (count % 3 == 0 && count % 5 == 0)
{
System.out.println("fizz buzz");
}
else
{
if (count % 3 == 0)
{
System.out.println("fizz");
}
else
{
if (count % 5 == 0)
{
System.out.println("buzz");
}
else
{
System.out.println(count);
}
}
}
}
endTime = System.currentTimeMillis();
executionTime = endTime - startTime;
System.out.println("Execution time: " + executionTime);
return executionTime;
}
Why is fizzBuzz2 faster? It does between 2 and 3 modulus calculations per run, fizzBuzz1 only ever does 2 calculations. I thought checking a stored boolean was faster than doing a calculation? What gives?