delphi

Advantages of using System.New instead of a local variable


Let’s go back to the basics. Frankly, I have never used the New and Dispose procedures before. However, after having read the New documentation and the included examples on the Embarcadero Technologies’s website and the Delphi Basics explanation of New, there are still some unresolved questions:


Solution

  • If you can use a local variable, do so. That's a rule with practically no exceptions. This results in the cleanest and most efficient code.

    If you need to allocate on the heap, use dynamic arrays, GetMem or New. Use New when allocating a record.

    Examples of being unable to use the stack include structures whose size are not known at compile time, or very large structures. But for records, which are the primary use case for New, these concerns seldom apply.

    So, if you are faced with a choice of stack vs heap for a record, invariably the stack is the correct choice.