Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster? ++, += or x + 1?

Tags:

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)?

like image 684
ApprenticeHacker Avatar asked Jun 25 '11 13:06

ApprenticeHacker


2 Answers

(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.

like image 154
Jon Skeet Avatar answered Sep 19 '22 15:09

Jon Skeet


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.

like image 41
David Heffernan Avatar answered Sep 18 '22 15:09

David Heffernan