C++ Code Optimization: 10 Tips And Tricks
C++ is a great enterprise programming language if you know how to get the most from its arcane features. Here are 10 tips to help you do so, and end up with high-performing applications for your business.
![](https://eu-images.contentstack.com/v3/assets/blt69509c9116440be8/blte8cf02b070d4ff8d/64cb4630d12303585e546b43/C_plus_plus_325.png?width=700&auto=webp&quality=80&disable=upscale)
When it comes to enterprise programming, C++ reigns supreme. That's one of the reasons why figuring out how to write the best C++ code possible is a hot topic on the Web. Another reason programmers come together to figure out best practices for C++ programming is the nature of the language itself. C++ gets its underlying structure from C, exists in multiple versions, and is wildly configurable and extensible. It is possible to use those qualities to write compact, efficient, elegant code in C++. It's equally possible to use those qualities to write a resource-devouring mess.
There are a lot of ways to nibble at the problem of bad C++ code. If you don't believe me, a quick Google search will prove the point. But which tips can have a larger impact on code quality? I took a look and came up with 10 that I believe might make a difference in the way your code behaves and the impact it has on the system as a whole.
[ Just getting started? Read 10 Top Programming Languages For Learning To Code.]
It's important to note that two of the tips in this article could apply to any programming language. They don't even require a computer. The rest, though, assume that you're actually writing some code in C++ and have the ability to compile it into executable code. Two of these are concerned with how you compile your code, leaving six that deal with the code you write.
As I mentioned upfront, these are suggestions that I think will have a real impact on your work. They're among thousands of tips that exist. Once you've reviewed them, tell me whether you think they're some of the best? I'd love to hear your thoughts and exchange some practical information with you in the comments section below. Which tactics and techniques have helped your code? Who knows, maybe you'll be featured in a future "how we code" article right here at InformationWeek.
**New deadline of Dec. 18, 2015** Be a part of the prestigious InformationWeek Elite 100! Time is running out to submit your company's application by Dec. 18, 2015. Go to our 2016 registration page: InformationWeek's Elite 100 list for 2016.
One of the problems that can hit any platform is an application that grabs the memory it needs, grabs more memory as it goes along, and never lets any memory go. It doesn't have to be a runaway process that chews through all the available memory and more. It can be an otherwise lovely app that doesn't effectively release the memory it requires.
The key to effectively letting go of memory is to use "delete []" when you're through with arrays (or their members), functions, and pointers. In general you'll want to make sure that you include the delete [] to clean up after every local function. Your users will be glad you did.
Even if you do everything right when it comes to garbage collection and temporary function use, if an application runs long enough it can end up fragmenting the available memory as single operators and objects are allocated and de-allocated. After a while, your application goes looking for a block of memory to do something important and can't find it -- at which point the whole system can come crashing to the ground. What can you do to keep your heaps healthy as long as possible?
When you're allocating (and de-allocating) objects, try doing it one array (or large block of objects) at a time rather than in onesies. Next, get comfortable with container class templates and use them as often as possible. Finally, think about the possibilities of static memory. I know dynamic memory is easy to use, but remember that there are consequences to getting hooked on a diminishing heap.
This one is very simple, very basic -- and the cause of thousands of hours of debugging effort. So let's go over it one more time:
C++ has two different operators based on the "=" symbol. Use one "=" and it's an operator that assigns value to a variable. "x=y" takes the value of y and assigns it to x. If you use the twin "==" symbol then you're asking whether x and y have the same value. That part is pretty simple.
The complication comes when you're typing rapidly and insert the wrong symbol into a program. The two symbols look so similar that it can take a long time to check through the code. It's entirely possible for the wrong symbol to give you code that functions -- only not in the way that you intended.
So be careful when you're typing. Be especially careful when you're typing those pesky "=" symbols.
There are programmers who like to make variables global "just in case." Resist the temptation. The big reason to be careful about this is because lots of global variables make for lots of opportunities for mischief, since errors in one function use global variables to cascade problems to other functions. It's far better to keep those variables local -- unless, of course, you need to communicate between functions. Then you should use global variables. Carefully.
The first part of this is all about execution code efficiency. If you need to increment or decrement a variable's value, don't go all DIY -- use the "++" or "- -" operator to get the job done.
Next, make sure that you're putting those operators in the right place. You can use these unary operators as either prefix or postfix, but there's a critical difference in what they do in each place. If you use them in prefix -- "a = ++b" -- then the value of b is incremented before it is assigned to a. In postfix usage -- "a = b++" -- the value of b is assigned to a, and then is incremented. It's the kind of difference that can be huge when you're using variables and unary operators to control loops and other structures.
"Make" is part of the development tool suite for pretty much every compiled language. If you're writing very simple, very short programs, you might be able to get away without calling on make. If you're writing code of any size or complexity, though, you should break your code into smaller logical pieces and use make to bring it all back together at the end of the process.
You can use make through the command line, but you'll give up a lot of functionality doing so. I don't have room here to teach you how to use make, but I can suggest you spend some time with the man file and figure out how to make make work for you. It will ultimately save you time and help you keep your code more compact and logical.
When you want to make sure that your code is solid, nothing beats compiling the same source with several different compilers. If you played fast and loose with standard code, or used novel libraries and templates, different compilers can give you different opinions about how "edgy" your work turned out to be.
Sure, you're going to have the compiler that's been blessed by your enterprise, and you should use that for the canonical compile run that delivers final executable code. When you're testing, though, grab a different compiler and see what happens. The best result could well be that you sleep a little better at night.
Flowcharts are very, very Old School, but when you're trying to figure out whether the logic of your code is sound, nothing beats seeing it visually represented in front of you. If you don't know how to flowchart, it's a skill worth learning. There are plastic templates to help you do paper versions, as well as software for desktop and most mobile operating systems. Draw your boxes and your arrows, and figure out the logic before you start writing code. Ultimately, you and your users will be much, much happier.
I've watched a lot of C++ programmers (and, to be fair, people programming in other languages) spend hour upon hour optimizing code that's implementing an inefficient algorithm. In the same way that flowchart analysis should be part of your development process, make sure that you've done the research to bring the best algorithms to the party. The results will be worth it.
So there are my 10 tips. What are yours? I'd love to benefit from your experience and share the knowledge of the InformationWeek programming community with a wider audience. I'll look forward to seeing you in the comments section below.
I've watched a lot of C++ programmers (and, to be fair, people programming in other languages) spend hour upon hour optimizing code that's implementing an inefficient algorithm. In the same way that flowchart analysis should be part of your development process, make sure that you've done the research to bring the best algorithms to the party. The results will be worth it.
So there are my 10 tips. What are yours? I'd love to benefit from your experience and share the knowledge of the InformationWeek programming community with a wider audience. I'll look forward to seeing you in the comments section below.
-
About the Author(s)
You May Also Like