This is not the typical debate in FizzBuzz code about how to handle repeated if statement. I believe that it is a matter of personal preference.
I am here to ask about the choice of repeated mathematical operation.
Usually the solution to a FizzBuzz code is to use the modulus operator on every iteration. However, I'm concerned with its performance impact.
From my knowledge, modulus operator is tightly connected with division operator, and has a considerable performance overhead compared to simple increment and decrement operator.
In addition, I don't believe compiler has the ability to analyse and optimise the use of modulus operator in a loop.
Hence, I give the alternative solution that uses only simple decrement operator. The following code are written in C++.
I seek insight on whether my approach will provide performance benefit, or if it is actually a horrible idea that worsen performance.
And if there are other ways I can optimize a FizzBuzz code even further. (I think in a modified FizzBuzz puzzle with lots of cases to compare against, a lookup table might be preferable)
Typical FizzBuzz solution.
for (unsigned int i = 1; i <= 1000000; ++i) {
if (!(i % 15))
std::cout << "FizzBuzz\n";
else if (!(i % 3))
std::cout << "Fizz\n";
else if (!(i % 5))
std::cout << "Buzz\n";
else
std::cout << i << '\n';
}
My optimized code.
static const unsigned int fa {3};
static const unsigned int fb {5};
unsigned int a {fa};
unsigned int b {fb};
for (unsigned int i = 1; i <= 1000000; ++i) {
--a, --b;
if (!a && !b) {
a = fa;
b = fb;
std::cout << "FizzBuzz\n";
} else if (!a) {
a = fa;
std::cout << "Fizz\n";
} else if (!b) {
b = fb;
std::cout << "Buzz\n";
} else {
std::cout << i << '\n';
}
}