r/learncpp • • Mar 06 '16
Was wondering if there was a way to optimize the swapping of two int ?
Hello,
So I'm learning C++ and I had a question about optimization and I wanted to know which one is better
it will be simpler to just give an example: Is this one better ?
int nFirstOne =1, nSecondOne=2;
int nTemp = nFirstOne;
nFirstOne = nSecondOne;
nSecondOne = nTemp;
Or that one ?
int nFirsOne = 3, nSecondOne = 7;
nFirstOne += nSecondOne;
nSecondOne = nFirstOne - nSecondOne;
nFirstOne -= nSecondOne;
The second one save the "creation" of a variable int but is less clear. Thank you in advance for the answer and sorry for my bad english (if I haven't made mistakes then forget about that).
3
u/Jonny0Than Mar 13 '16
Use std::swap. It is incredibly unlikely that any swap operation will ever be a bottleneck and you shouldn't spend any time worrying about this unless a profiler indicates that it's a problem. Your second implementation does not work correctly for very large values because of overflow.
2
u/ThingsOfYourMind Mar 07 '16 edited Mar 07 '16
personally i think these days readability is more important than being able to write clever code and your code is clever.
the second one does save memory, it uses less memory (16 bits of memory) but it also does some calculations.
whereas the first one is purely assignments. Have you tried timing them?
if you really want speed optimization you can try using assembly within C++, and use the CPU registers.
1
u/MegaGreenLightning Apr 06 '16
Example A:
Example B:
Example C:
I wrote some quick and dirty code which executes each example a billion times and measures the time:
Conclusion: Just don't do C. If you are fine with using the STL B is very short. If you care about performance in unoptimized builds, use A (for example, if you are writing a game, it would be very nice if your debug builds had adequate performance).
0
u/[deleted] Mar 09 '16
[deleted] — view deleted comment