Don't use very large local variables or members

Auto (local) variables and members of objects that are themselves auto variables are allocated on the stack. However, stack sizes are platform dependent, and in a layered environment, the thread stack sizes can be up to the host operating system. Large data structures can blow the stack as your program moves between platforms and hosts.

Conversely, if you decide to place large objects on the heap, you might notice that it takes several hundred microseconds to allocate them. Follow these guidelines when trying to determine whether to put a variable on the stack (as part of another object) or on the heap:

Don't allocate more than a few kilobytes at a time on the stack. This is a rule of thumb, and you'll have to use your best judgment. Think of it as the point where you should start wondering whether something should really be on the stack. Talk to an architect if you have questions. In addition, avoid algorithms that use recursion in an unbounded fashion, as the default stack always has some preset size. Algorithms that use recursion in a bounded fashion, such as Quicksort, are acceptable. The deeper you recurse, the less stack space you should use on each recursion.

Use the heap for larger objects, not the stack, regardless of performance. There are a number of custom storage allocation techniques you can use (such as pooling objects for reuse) to cut down on the overhead for large heap objects.

For information about memory issues with local arrays, see "Avoid using arrays as local variables or object fields" on page 80.

[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker