Suppose there is some function that runs every 0.5 seconds:

procedure func(); var list: TStringList; str: string; begin list := TStringList.Create(); str := 'STRING'; ... end; 

The question is: will local variables be automatically deleted from memory when the function is processed? And is there a mechanism similar to the Garbage Collector (Java, C #) in Delphi?

    3 answers 3

    Memory allocated for variables of built-in data types (for example, integer , real , string , static arrays, etc.) will be freed automatically. And for instances of classes will not, here you have to destroy instances yourself through Destroy or FreeAndNil(obj) .

    Delphi generates native code. And C # and Java bytecode, which is used by the virtual machine and it also monitors memory usage. In principle, in Delphi you can implement this for instances of classes, but then all classes must be inherited from TInterfacedObject . In this case, if no one refers to a class instance, it is automatically destroyed.

    • one
      In your case, the memory allocated for the str variable will be freed. The memory allocated for the reference variable list will also be freed (this is 4 or 8 bytes depending on the platform you are compiling under), but the area of ​​memory to which it refers will not be freed. - artkil
    • one
      Java and C # are not executed on the virtual machine that you are! Your information is outdated by 5 years. Now JIT compiles to native code. - VladD
    • one
      The presence of GC does not contradict the compilation into native code, for example D. - IronVbif

    In Delphi for mobile platforms (only for DCCIOS32, DCCIOS32ARM, and DCCAARM - this is iOS and Android) is now ARC (Automatic Reference Counting) . This is not a garbage collector, but it works like. In essence, this is the same as it was with interfaces, but now it is a "native" property for other classes / objects. In your example using ARC, everything will be fine.

    Yes, they will be deleted. That is, you can easily use the same local variables in different functions.

    • In this case, we are not talking about using the variables of the same name in different functions :) I wonder what happens after the function is executed, and not at the compilation stage. - AseN
    • Actually, I meant what is written above. But he put it like this :) - vdk company