Friday, 17 January 2014

Tips to reduce running time in C++

Here are a few tips to reduce to reduce running time in C++:

1. Write ++i in for loops:
Whenever you write variable++, a temporary variable is generated which is unnecessary overhead (unless you want this specifically) . In this case it doesn't matter because the compiler will optimize an int datatype for you, but if you have huge iterators, this can make a small difference in your speed.


2. Never pass objects by copy unless you have to:
Whenever you call funct(string , string ) it will copy your strings into the function. Maybe this is what you want, but many people unknowingly do this. Instead do this, funct( const string & , const string & ) . This passes a constant reference of your string to the function. The reason to add const is that you can take a const reference to a temporary variable. (e.g. funct("Hello","World") will not work if you do funct (string & , string & ) )

3. Use inline functions for small functions:
Marcos are bad news. For small functions append the word inline in front of it. The preprocessor will just copy paste the code wherever it is called. This is much faster but you have to be careful with them.

4. Know how to use STL:
STL is a wonderful library and can be very helpful if you know how to use it. However, STL objects are on the heap ( i.e. dynamic memory) so use them judiciously.

No comments:

Post a Comment