4.10. C++ Features to Use and AvoidΒΆ
Some C++ features incur in a run-time penalty. Other features are handled completely at compile-time and thus do not cause a run-time penalty. A full discussion of which C++ features do and do not incur a run-time penalty is outside the scope of this document; discussion is available from several sources on the internet and in print.
Some features that do incur a run-time penalty are so useful in providing the desired level of abstraction and/or safety, that you should consider using them anyway. Here are some guidelines for some of the more commonly-used features:
These features have potential run-time overheads. Consider whether the benefits are worth the cost:
Calls to
new()
, although this is essentially no more or less expensive thanmalloc()
Use of the Standard Template Library (STL), mainly due to hidden calls to
new()
Exceptions / exception handling
Run-Time Type Information (RTTI)
Multiple inheritance
Virtual functions (although the run-time cost is usually small)
Use these features freely, as they have little to no run-time overhead:
Templates
Operator overloading
Function overloading
Inlining
Well-designed inheritance. In particular, calling a member function of a derived class incurs no penalty if the object type is known at compile-time.
The following features improve performance and should be used where possible:
Use of
const
Use of
constexpr
Passing objects by-reference instead of passing objects by-value
Constructs and expressions that can be evaluated at compile-time versus run-time