+ 1
Order of if-else blocks
Would it make any difference or have any impact on performance if I switched those 2 if blocks? if (i % 3 == 0) { cout << "Fizz" << endl; } else if (i % 5 == 0) { cout << "Buzz" << endl; } I know it's not a question worth asking, but I'm wondering if the program would run slightly slower if 5 is checked first because it's greater than 3 https://code.sololearn.com/ca63KT1dN2Q3/?ref=app
2 odpowiedzi
+ 2
The if condition is always checked, the else if condition only when the if condition is false.
So how many times the else if condition has to be checked depends on the false ratio of the if condition. The higher the ratio the more often the else if condition has to be checked.
For i % 3 == 0 that ratio is 2/3.
For i % 5 == 0 that ratio is 4/5.
So the order you used is slightly more efficient than the alternative.
+ 1
Simon Sauter
Thanks for the clarity!