Detect Unused Objects

Detect Unused Objects

Improper use of objects and object references can cause your application’s objects to stay resident in memory. Such “memory leaks” often causes system performance degradation and prevents your application from scaling well over time. Instead of using complex system utilities and third-party tools to detect such “bad code” in your application, you can put VB5/VB6’s event technology to work for you.

Create an ActiveX DLL-such as ListObjects.dll-with a single class: ResidentObjs.cls. Add a method to raise an event. You may call this subroutine DetectAllObjects. Declare an event in the Declarations section of the class:

 Option ExplicitPublic Event ObjectNotification()Public Sub DetectAllObjects()	DoEvents	' let the system do its job.	RaiseEvent ObjectNotification()End sub

In your application, add a reference to ListObjects.dll to your project. Then declare a global variable in a BAS module as a ResidentObjs type, and instantiate this object variable at Application startup:

 Sub Main()	Set oListObject = New ListObject.ResidentObjsEnd Sub

In each class of your project, you must declare a ResidentObjs variable using WithEvents. Set this object variable to the global variable upon class initialize or some other class function that is called each time you create an object of that class. In the event function, you can add any code that warns you about the current object instance. For example, you can add Debug.Print, or some code that writes the class name to a file.

At any suitable point in your project code, you can call DetectAllObjects(). The number of times the event function gets called is the number of objects resident in your memory at that time. To zero in on only some of the main classes, you can limit the DLL object declaration to only those classes.

See also  How HealthStream Learning Center Supports Healthcare Education and Compliance

How does this work? Events are a form of anonymous broadcast messages. They are sent to every object instance in your application. Hence, this simple yet powerful mechanism can detect invalid objects. In fact, you can step into the code to actually see the event function being called several times.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist