Search code examples
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:

  • What are the advantages of using System.New instead of a local variable, other than just spare a tiny amount of memory?

    Common code examples for New are more or less as follows:

        var
            pCustRec : ^TCustomer;
        begin
            New(pCustRec);
            pCustRec^.Name := 'Her indoors';
            pCustRec^.Age  := 55;
            Dispose(pCustRec);
        end;
    
  • In what circumstances is the above code more appropriate than the code below?

        var
            CustRec : TCustomer;
        begin
            CustRec.Name := 'Her indoors';
            CustRec.Age  := 55;
        end;
    

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.