Hello, dear experts. Actually the question:
What is the best way to allocate memory for a dynamic array β€” SetLength or AllocMem ? For example:

 type TMyArray = array of Integer; var MyArray: TMyArray; PMyArray: ^TMyarray; begin //Π’Π°Ρ€ΠΈΠ°Π½Ρ‚ с SetLength SetLength(MyArray,High(Word)); .....ΠΊΠ°ΠΊΠΈΠ΅-Π½ΠΈΠ±ΡƒΠ΄ΡŒ дСйствия..... //Π’Π°Ρ€ΠΈΠ°Π½Ρ‚ с AllocMem try PMyArray := AllocMem(High(Word)*SizeOf(Word)); ................. ΠΊΠ°ΠΊΠΈΠ΅-Π½ΠΈΠ±ΡƒΠ΄ΡŒ дСйствия ................. finaly FreeMem(PMyArray,High(Word)*SizeOf(Word)); end; 

Or no difference?

    2 answers 2

    If you need for internal use, then definitely SetLength . Since the machine gets control of the output outside the array, typing, automatic release, a simple increase in size and other buns.

    In the version with AllocMem you need to do everything with pens. Will the gain in speed? much doubt. I think that SetLength uses AllocMem inside.

    • One important point, if the memory is allocated with pom. SetLength then when you try to add several records to the array (increase its length) your array will be moved to a new place in the memory without the data it contained, a couple of times it was torn on such .. - Vladimir Klykov
    • one
      Strongly doubt. Here is an example var a: array of integer; begin SetLength (a, 3); a [2]: = 10; SetLength (a, 10,000); ShowMessage (inttostr (a [2])); end; will output 10. Works great. - KoVadim
    • one
      Perhaps you stored objects in such an array. Here there can be any features. For example, when reducing the size, destructors will not be automatically called. But for objects it is better to use TList and TCollection (or their heirs). - KoVadim
    • In the array, there really were references to classes (objects), but the problem arose precisely when the array was increased. var a: array of pointer; I: integer; begin for i: = 0 to 1000 do begin SetLength (a, length (a) +2); a [max (a)]: = TStringList.create; TStringList (a [max (a)]). Text = 'SomeText'; end; // another passage through the array, some of the elements of the array will be empty, emptying will occur when it is impossible to get more space for new elements in the same place where the array is located - help on Delphi and personal experience. end; - Vladimir Klykov
    • This unpleasant moment in a normal way did not find how to get around, I had to use bidirectional lists (although they should have been used there initially ...) - Vladimir Klykov
     SetLength(a,length(a)+2); 

    So this is because you are stuffing empty elements into this array. Of course they will be there.