I am using C# (This question is also valid for similar languages like C++) and I am trying to figure out the fastest and most efficient way to increment. It isn't just one or two increments, in my game, its like 300 increments per second. Like the Frames of every sprite on the screen are incrementing, the speed and positions of my rpg character, the offset of the camera etc. So I am thinking, what way is the most efficient? e.g for incrementing 5 y_pos
on every movement I can do:
1.
Player.YPos += 5;
2.
Player.YPos = Player.YPos + 5;
3.
for (int i = 0; i < 5; i++) { Player.YPos++; }
Which is the most efficient (and fastest)?
(Answer specific to C# as C++ may vary significantly.)
1 and 2 are equivalent.
3 would definitely be slower.
Having said that, doing this a mere 300 times a second, you wouldn't notice any difference. Are you aware of just how much a computer can do in terms of raw CPU+memory in a second? In general, you should write code for clarity as the most important thing. By all means worry about performance - but only when you have a way to measure it, in order to a) tell whether you need to worry, and b) whether any changes actually improve the performance.
In this case, I'd say that option 1 is the clearest, so that's what I'd use.
Options 1 and 2 will result in identical code being produced by the compiler. Option 3 will be much slower.
It's a fallacy that i++
is faster than i += 1
or even i = i + 1
. All decent compilers will turn those three instructions into the same code.
For such a trivial operation as addition, write the clearest code and let the compiler worry about making it fast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With