You can improve performance by reducing the number of times you dynamically allocate memory. Every time you call the new operator a certain amount of space is allocated from the heap. This space is always aligned at 16 bytes, which is suitable for storage of any object type. In addition, 32 extra bytes are taken from the dynamic heap for bookkeeping. This means that even if you only want one byte, 48 bytes are allocated from the dynamic heap, 32 bytes for bookkeeping and 15 bytes for padding. When the current space allocation in the heap is used up, storage allocation is slower:
ptr1 = new char[12]; ptr2 = new char[4];
In the code above, 96 bytes are taken from the heap (including 64 bytes for bookkeeping and 16 bytes for padding) and new is used twice. This code can be rewritten as:
ptr1 = new char[16]; ptr2 = ptr1 + 12;
Only 48 bytes are taken from the heap and the new operator is only used once. Because you reduce the dynamic space allocation requirement, less storage is taken from the heap. You may gain other benefits such as a reduction in page faults. Because there are fewer calls to the new operator, function call overhead is reduced as well.
(C) Copyright IBM Corporation 1992, 2005. All Rights Reserved.