| Prev | Next | Start of Chapter | End of Chapter | Contents | Glossary | Index | Comments | (4 out of 5)

Preventing Memory Leaks

Memory leaks occur when an application causes memory use to increase continually over time. The most common cause of application memory leaks is the creation of transient objects that the application never deletes. Over time, G2 must allocate more memory to hold these items, until memory is finally exhausted and G2 is forced to shut down.

This section offers some techniques for preventing memory leaks from occurring and diagnosing their source.

For detailed information about correcting memory leaks, see the G2 Reference Manual.

Pair Create and Delete Statements within the Same Procedure

Most memory leaks occur when you have a create action that does not match with a delete action. Remember, the create action creates a transient item, which remains allocated in memory, unless you either delete it or make it a permanent part of your KB.

The best way to prevent leaks is to match every create with a delete within the same procedure. This allows the developer to check for potential leaks by simply visually inspecting the code. The exception to this guideline are procedures whose specific purpose is to create objects.

For example, if you want a procedure to return a list of all items of the class tank, you have two possibilities:

The first option creates an item list that needs to be deleted by the calling procedure, which is easy to forget to do. The second option forces you to create the item list that will contain the tanks, so you will be less likely to forget to delete the list. The second option is preferred because the create and delete are in the same procedure. Furthermore, the second option gives the developer the additional flexibility of using an existing list.

Avoid Generating Random Names

In general, do not design applications in which you name objects with randomly generated symbols. Because symbols are never reclaimed by G2, this approach can lead to unbounded memory growth. However, there are cases, such as naming data series in charts and graphs, where you cannot avoid generating random names.

One approach is to recycle symbols by creating a list of symbols which you recycle when the object requiring a name is deleted.

| Prev | Next | Start of Chapter | End of Chapter | Contents | Glossary | Index | Comments | (4 out of 5)

Copyright © 1997 Gensym Corporation, Inc.