Actually, your code is wrong.
Now you are doubling the memory usage.
SetLength creates a big string, then in the loop, you add more to it...
If you wish to pre-allocate the length of the string, then you need to do it this way:
Function MultiplyStrWithPreallocate(aStr: String; aMultiplier: Integer): String;
Var i, pos: Integer;
Begin
SetLength(Result, Length(aStr) * aMultiplier);
pos := 1;
For i := 1 To aMultiplier Do
Begin
move(aStr[1], Result[pos], Length(aStr) * sizeOf(Char));
Inc(pos, Length(aStr));
End;
End;
Here is what is going on behind the scene, when you call:
Result := Result + aStr;
the memory manager creates a new temporary string, assigns the content of "result" and "aStr" to it. That new temporary Strings is then assigned to "result" which in turn decreases the reference counter to the String that result is refering... in that case to 0, which causes the memory manager to release that String.
So for a short period of time, both, the original "result" and the "result"+"aStr" are in memory.
And for each for-loop-iteration, you basically have a copy operation of the whole string.
My above optimization using move reduces both of those concerns. There is just one memory allocation, and only a few bytes are copied in each for-loop-iteration