I’m currently going through the Learn Java course. I completed the Fizz Buzz activity but I’m not sure if this is the best way to do it. Can anyone with some experience let me know please. Thanks
Yes, that’s about the most you can get out of it. Instead of using continue you can chain your if’s into else-if’s. But that doesn’t impact performance, they are both linear.
Thanks for the reply!
Would a switch/case with a single test be more efficient? (Mathematically you can do this with a single modulo operation…)
Asking as I am not hugely familiar with Java; familiar enough that I can solve this in the way I suggest (with a switch), but not sufficiently to know how to build a timing wrapper to verify which is faster over n
It would be negligible for most cases. If one needs to have performant code where such a change had impact, they’d probably be using C or C++ (JVM doesn’t come close here), even then it seems like there are compiler and architecture specific considerations. I wouldn’t be surprised if compiler optimization makes it close in 99% of all cases in standard setups (maybe more). (random discussion on this: Reddit - Dive into anything)
So in case you’re curious as to what this discussion is referring to @serhaan02, for it to be useful you’d have to go over runtime analysis (big-o), architecture, and compilers. It can be overwhelming since all of those can be semester long courses so I didn’t think to mention it (big-o i guess can be just 2-3 lectures for the basics, if you have calculus 2 in your arsenal).
It can be a fun topic in computing if you’re interested, just not strictly required (the courses are great fundamentals and those you should look into, but what’s not as urgent is the performance of switch vs if-else).