Hands-On High Performance Programming with Qt 5
上QQ阅读APP看书,第一时间看更新

What your compiler can do for you

C++ is a high-level programming language and offers many abstract programming constructs that make programmers amazingly productive. But, the higher the abstraction level is, the greater is the threat of obscuring the low-level performance details. Optimally, we want to write clear, understandable and maintainable code but without compromising performance in the process. For this reason, compilers will try to optimize the code automatically and improve the performance so that we can have the better of two worlds—readable code and good machine-level performance. 

One must say that compilers have become quite sophisticated in doing so over the years. They have many amazing tricks up their sleeves as we will see, so we should be better focusing on clear, understandable code rather than trying to optimize code manually that then ends up being cryptic, fragile, and hard to maintain. This is a classic case of premature optimization—doing something we don't need to do as the compiler will do that anyway. It can even have a detrimental influence on performance, as our attempts to micro-optimize may prevent the compiler from applying its standard tricks.

We will now have a look at what exactly compilers are trying to do. And don't worry, there's enough work left for us! Compilers cannot replace a bad algorithm with a more efficient one or change the layout of a data structure to improve its locality—we have to do this.