1. Computing & Technology

Discuss in my forum

Creating Components Dynamically (at Run-Time)

Dynamic Creation Notification Performance

By , About.com Guide

Creating Components Dynamically (at Run-Time)

A test program was created in Delphi to time the dynamic creation of 1000 components with varying initial component counts. The test program appears at the bottom of this page. The chart shows a set of results from the test program, comparing the time it takes to create components both with owners and without. Note that this is only a portion of the hit. A similar performance delay can be expected when destroying components. The time to dynamically create components with owners is 1200% to 107960% slower than that to create components without owners, depending on the number of components on the form and the component being created.

Analyzing the Results

Creating 1000 owned components requires less than a second if the form initially owns no components. However, the same operation takes roughly 10 seconds if the form initially owns 9000 components. In other words, creation time is dependant on the number of components on the form. It is equally interesting to note that creating 1000 components that are not owned takes only a few milliseconds, regardless of the number of components owned by the form. The chart serves to illustrate the impact of the iterative Notification method as the number of owned components increase. The absolute time required to create an instance of a single component whether owned or not, is negligible. Further analysis of the results is left to the reader.

The Test Program

You can perform the test on one of four components: TButton, TLabel, TSession, or TStringGrid (you can of course modify the source to test with other components). Times should vary for each. The chart above was from the TSession component, which showed the widest variance between creation times with owners and without.

Warning: This test program does not track and free components that are created without owners. By not tracking and freeing these components, times measured for the dynamic creation code more accurately reflect the real time to dynamically create a component.

Download Source Code

Warning!

If you want to dynamically instantiate a Delphi component and explicitly free it sometime later, always pass nil as the owner. Failure to do so can introduce unnecessary risk, as well as performance and code maintenance problems. Read the "A warning on dynamically instantiating Delphi components" article to learn more...

©2012 About.com. All rights reserved.

A part of The New York Times Company.