Because C++ objects are often allocated from the
heap and have limited scope, memory use affects performance more in
C++ programs than it does in C programs. For that reason, consider
the following guidelines when you develop C++ applications:
- In a structure, declare the largest aligned members first. Members
of similar alignment should be grouped together where possible.
- In a structure, place variables near each other if they are frequently
used together.
- Ensure that objects that are no longer needed are freed or
otherwise made available for reuse. One way to do this is to use an object
manager. Each time you create an instance of an object, pass the
pointer to that object to the object manager. The object manager maintains
a list of these pointers. To access an object, you can call an object
manager member function to return the information to you. The object
manager can then manage memory usage and object reuse.
- Storage pools are a good way of keeping track of used memory (and
reclaiming it) without having to resort to an object manager or reference
counting. Do not use storage pools for objects with
non-trivial destructors, because in most implementations the destructors
cannot be run when the storage pool is cleared.
- For XL
C/C++ for AIX®, V11.1 level 11.1.0.03
and higher, consider using the <ssostring> header
file that is supplied by IBM for programs that create large numbers of
small strings. The header file uses the Small Buffer Optimization
(SBO) technique that can reduce the number of dynamic memory allocations
at program execution time so runtime overhead is reduced and runtime
performance is improved. The public interface of the header file is
identical to the <string> header file in the
standard C++ library. For more information about using the header
file, see Small String Optimized (SSO) string class and <string>.
- Avoid copying large, complicated objects.
- Avoid performing a deep copy if a shallow copy is
all you require. For an object that contains pointers to other objects,
a shallow copy copies only the pointers and not the objects to which
they point. The result is two objects that point to the same contained
object. A deep copy, however, copies the pointers and the objects
they point to, as well as any pointers or objects contained within
that object, and so on. A deep copy must be performed in multithreaded
environments, because it reduces sharing and synchronization.
- Use virtual methods only when absolutely necessary.
- Use the "Resource Acquisition
is Initialization" (RAII) pattern.
- Use shared_ptr and weak_ptr.