I'm working on a game, in one class I have for now 4 flags (I use boolean), but I'd like to switch to int and make each flag a bit. Some of my flags are checked inside the main loop every time, so looking to the future (where I could have more flags): will my flagset slow down my program? Is it better to keep using boolean?
-
6Do you have some reason to believe that the performance of your game will hinge on how a bitflag is implemented? Write your code cleanly first, then profile, and only optimize after you profile.Nicol Bolas– Nicol Bolas2015-12-10 15:26:26 +00:00Commented Dec 10, 2015 at 15:26
-
5This is a classic case of premature optimization. Bitwise operators and boolean checking are so insanely fast as to be irrelevant unless you're doing hundreds of millions of them a second. At which point...almost anything else you're doing is going to be costing more time.Draco18s no longer trusts SE– Draco18s no longer trusts SE2015-12-10 15:27:48 +00:00Commented Dec 10, 2015 at 15:27
-
@NicolBolas In one method I have to compare the boolean, and in the other I have to get the value of the flag and compare it. I'm trying to write as efficient as possible code. Downvoters pls explain...Xriuk– Xriuk2015-12-10 15:28:59 +00:00Commented Dec 10, 2015 at 15:28
-
3@RomanHudylko: "I'm trying to write as efficient as possible code." Why? Do you think it'll be worth it? That's what I asked: is this case an actual performance problem? Otherwise, do it whatever way makes the code easier to read. The time it took you to write this question is probably longer than the number of ms that any response would actually save your application. Don't spend time making code faster in negligible areas.Nicol Bolas– Nicol Bolas2015-12-10 15:30:45 +00:00Commented Dec 10, 2015 at 15:30
-
1I have been programming for more than 30 years. On at least two occasions I have managed to correctly guess where the performance problem was before I actually measured.Martin Bonner supports Monica– Martin Bonner supports Monica2015-12-10 17:25:43 +00:00Commented Dec 10, 2015 at 17:25
2 Answers
Optimization should hing only on how often you are actually going to use something. This is a big killer on programming efficiency. The way to determine IF you need to optimize something is figure out how often it will actually be used.
So, if you are only going to use something once or twice a second or when the user manually does something then the answer is most likely going to be "don't bother". On the other hand if the optimization is in something that runs continuously a thousand times a second then the answer is "maybe". The later depends on how many clocks the operation is eating. The case of flag checking the answer is most likely no as the clock ticks for either are negligible. The better optimization might be on why you are calling that function, routine, etc ... so many times to begin with.