ILE C/C++ Programmer's Guide

Minimizing Dynamic Memory Allocation Calls

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.

Note:
If you allocate space by incrementing pointers, you must guarantee the proper alignment when you allocate pointers (or aggregates which can contain pointers) because pointers require 16-byte alignments. There is a performance degradation for data types such as float if they are not allocated on their natural boundaries because these data types have a natural alignment of word or doubleword.


[ Top of Page | Previous Page | Next Page | Table of Contents ]