|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
Optimizing Your Code
Optimization is the process of fine-tuning executable performance for best performance and smallest code size. Visual C++ provides the following mechanisms for optimizing code:
Pragmas and keywords you can insert into your source code.
Compiler options that support optimizations; see Compiler Options by Category.
For details on how good programming practices can improve program performance, see:
Microsoft Visual Studio and Windows 2000 Scalability Center (http://msdn.microsoft.com/vstudio/centers/scale/default.asp)
Because optimization changes the code created by the compiler, it is best to optimize your code after you have fully tested and debugged it. That way, you can debug code that closely matches your source code and not worry about the effects of optimization. Once you apply optimizations, you should test your code again. Occasionally, code will behave differently when optimizations are applied. In that event, you may need to debug optimized code. Also see Common Problems When Creating a Release Build for more information.
Optimized code sometimes gives different answers not because of an error but because optimization changes the order of calculations, resulting in slightly different results due to the limits of floating-point precision.
You may also notice some additional warning messages when you compile your code with optimization. This is normal behavior because some warnings relate only to optimized code. If you pay attention to these warnings, you can avoid most of the problems associated with optimization.
Paradoxically, optimizing a program for speed can sometimes cause code to run slower because some optimizations for speed increase code size. Inlining functions, for example, eliminates the overhead of function calls, but inlining too much code may make your program so large that the number of virtual-memory page faults increases. Therefore, the speed gained from eliminating function calls may be lost to memory swapping. For this reason, it is a good idea to measure the performance of your program before and after you apply optimizations. For general guidelines on how best to optimize your application, see.
For additional topics on optimization, see: