This is Delphi 2009, so Unicode applies.
I had some code that was loading strings from a buffer into a StringList as follows:
var Buffer: TBytes; RecStart, RecEnd: PChar; S: string;
FileStream.Read(Buffer[0], Size);
repeat
... find next record RecStart and RecEnd that point into the buffer;
SetString(S, RecStart, RecEnd - RecStart);
MyStringList.Add(S);
until end of buffer
But during some modifications, I changed my logic so that I ended up adding the identical records, but as a strings derived separately and not through SetString, i.e.
var SRecord: string;
repeat
SRecord := '';
repeat
SRecord := SRecord + ... processed line from the buffer;
until end of record in the buffer
MyStringList.Add(SRecord);
until end of buffer
What I noticed was the memory use of the StringList went up from 52 MB to about 70 MB. That was an increase of over 30%.
To get back to my lower memory usage, I found I had to use SetString to create the string variable to add to my StringList as follows:
repeat
SRecord := '';
repeat
SRecord := SRecord + ... processed line from the buffer;
until end of record in the buffer
SetString(S, PChar(SRecord), length(SRecord));
MyStringList.Add(S);
until end of buffer
Inspecting and comparing S and SRecord, they are in all cases exactly the same. But adding SRecord to MyStringList uses much more memory than adding S.
Does anyone know what's going on and why the SetString saves memory?
Followup. I didn't think it would, but I checked just to make sure.
Neither:
SetLength(SRecord, length(SRecord));
nor
Trim(SRecord);
releases the excess space. The SetString seems to be required to do so.
If you concatenate the string, the memory manager will allocate more memory because it assumes that you add more and more text to it and allocates additional space for future concatenations. This way the allocation size of the string is much larger than the used size (depending on the used memory manager). If you use SetString, the allocation size of the new string is almost the same as the used size. And when the SRecord string goes out of scope and its ref-count becomes zero, the memory occupied by SRecord is released. So you end up with the smallest needed allocation size for your string.
Try to install memory manager filter (Get/SetMemoryManager), which passes all calls to GetMem/FreeMem to default memory manager, but it also performs stats garhtering. You'll probably see that both variants are equal in memory consumption.
It's just memory fragmentation.
Related
I need to find a certain string, in a text file, from bottom (the end of the line).
Once the string has been found, the function exit.
Here is my code, which is working fine. But, it is kind of slow.
I meant, I run this code every 5 seconds. And it consumes about 0.5% to 1% CPU time.
The text file is about 10 MB.
How to speed this up? Like, really fast and it doesn't consume much CPU time.
function TMainForm.GetVMem: string;
var
TS: TStrings;
sm: string;
i: integer;
begin
TS := TStringList.Create;
TS.LoadFromFile(LogFileName);
for i := TS.Count-1 downto 0 do
begin
Application.ProcessMessages;
sm := Trim(TS[i]);
if Pos('Virtual Memory Total =', sm) > 0 then
begin
Result := sm;
TS.Free;
exit;
end;
end;
Result := '';
TS.Free;
end;
You can use a TMemoryStream and use LoadFromFile to load the complete file content.
The you can cast the property Memory to either PChar or PAnsiChar or other character type depending on file content.
When you have the pointer, you can use it to check for content. I would avoid using string handling because it is much slower than pointer operation.
You can move the pointer from the end of memory (use Stream.Size) and search backward for the CR/LF pair (or whatever is used as line delimiter). Then from that point check for the searched string. If found, you are done, if not, loop searching the previous CR/LF.
That is more complex than the method you used but - if done correctly - will be faster.
If the file is to big to fit in memory, specially in a x32 application, you'll have to resort to read the file line by line, keeping only one line, going to the end of file. Each time you find the searched string, then save his position. At the end of file, this saved position - if any - will be the last searched file.
If the file is really very large, and the probability that the searched string is near the end, you may read the file backward (Setting TStream.position to have direct access). block by block. Then is each block, use the previous algorithm. Pay attention that the searched string may be split in two blocks depending on the block size.
Again, depending on the file size, you may split the search in several parallel searches using multi threading. Do not create to much thread neither. Pay attention that the searched string may be split in two blocks assigned to different threads depending on the block size.
I want to convert a 2GB file to an array of byte with Delphi. I use this function, then load file into memory Stream to get bytes. But I get error "Out of memory". How I can solve this problem?
type
TByteArray = Array of Byte;
function StreamToByteArray(Stream: TStream): TByteArray;
begin
// Check stream
if Assigned(Stream) then
begin
// Reset stream position
Stream.Position:=0;
// Allocate size
SetLength(result, Stream.Size);
// Read contents of stream
Stream.Read(result[0], Stream.Size);
end
else
// Clear result
SetLength(result, 0);
end;
//////then in button control i use:
var
strmMem: TMemoryStream;
bytes: TByteArray;
begin
strmMem:=TMemoryStream.Create;
if OpenDialog1.Execute then
strmMem.LoadFromFile(OpenDialog1.FileName);
bytes:=StreamToByteArray(strmMem);
strmMem.Free;
A 32 bit process has a total of 4GB of address space. Unless it has the large address aware flag available, only 2GB of that address space is available to it.
You are attempting to load a 2GB file into memory, in a contiguous block of address space. There is no chance of you being able to succeed. Even with a large address aware 4GB address space there's little hope for you finding a contiguous 2GB block of address space.
Furthermore, you are also attempting to read the file into memory twice, so you actually need two 2GB contiguous blocks. One for the stream, and one for the array. This is a result of you using the memory stream anti-pattern as described below.
Some options:
Switch to a 64 bit process, or
load the entire file, but in discontinuous blocks, or
process the file piece by piece, in smaller chunks.
Regarding the use of a memory stream, this is a recurring anti-pattern. I'd say that >90% of the uses of memory streams that we see here in the Delphi Stack Overflow tag are needless and wasteful.
The mistake is to load into memory just to be able to copy to some other memory. You are trying to read the file into an array. So read it directly into an array. The memory stream is pointless. Use a file stream. Read from the file stream into the array. That way you only load a single copy of the file into memory.
Of course, you'll sill struggle to put a 2GB file into memory even with that change, but you should still aim to hold only one copy of the data in memory.
How could I get the total amount of memory, that allocated by FastMM?
I've tried that:
function GetTotalAllocatedMemory: Cardinal;
var
MMState: TMemoryManagerState;
begin
GetMemoryManagerState(MMState);
Result := MMState.TotalAllocatedMediumBlockSize + MMState.TotalAllocatedLargeBlockSize;
end;
Is it correct?
Anyways it returns something strange. It 5 times less than a value which I can see in Windows task manager. I believe that the amount of memory allocated by a Delphi application equals FastMM allocated memory plus some system overhead. Am I wrong?
Use this:
//------------------------------------------------------------------------------
// CsiGetApplicationMemory
//
// Returns the amount of memory used by the application (does not include
// reserved memory)
//------------------------------------------------------------------------------
function CsiGetApplicationMemory: Int64;
var
lMemoryState: TMemoryManagerState;
lIndex: Integer;
begin
Result := 0;
// get the state
GetMemoryManagerState(lMemoryState);
with lMemoryState do begin
// small blocks
for lIndex := Low(SmallBlockTypeStates) to High(SmallBlockTypeStates) do
Inc(Result,
SmallBlockTypeStates[lIndex].AllocatedBlockCount *
SmallBlockTypeStates[lIndex].UseableBlockSize);
// medium blocks
Inc(Result, TotalAllocatedMediumBlockSize);
// large blocks
Inc(Result, TotalAllocatedLargeBlockSize);
end;
end;
You are comparing apples and oranges.
FastMM memory is netto usage of memory allocated through FastMM.
This does not include at least these:
FastMM overhead
Windows overhead of blocks allocated by FastMM on your behalf
Windows overhead of things not allocated by FastMM (like the space occupied by DLL's in your process space)
for GUI apps: overhead of GDI, GDI+, DirectX, OpenGL and other storage for visual objects allocated on your behalf.
--jeroen
For the process memory use this:
//------------------------------------------------------------------------------
// CsiGetProcessMemory
//
// Return the amount of memory used by the process
//------------------------------------------------------------------------------
function CsiGetProcessMemory: Int64;
var
lMemoryCounters: TProcessMemoryCounters;
lSize: Integer;
begin
lSize := SizeOf(lMemoryCounters);
FillChar(lMemoryCounters, lSize, 0);
if GetProcessMemoryInfo(CsiGetProcessHandle, #lMemoryCounters, lSize) then
Result := lMemoryCounters.PageFileUsage
else
Result := 0;
end;
I also have faced this situation:
Anyways it returns something strange. It 5 times less than a value
which I can see in Windows task manager. I believe that the amount of
memory allocated by a Delphi application equals FastMM allocated
memory plus some system overhead. Am I wrong?
and wasted several hours trying to find out where all the memory is. My app occupied 170 Mb according to Task manager but FastMM's stats was showing total size of allocated blocks ~13 Mb:
12565K Allocated
160840K Overhead
7% Efficiency
(excerpt from FastMM LogMemoryManagerStateToFile procedure output). Finally I realized that this enormous overhead is caused by FullDebug mode. It keeps stacktraces for every allocation so if you've many tiny memory blocks allocated (my app had UnicodeString x 99137, Unknown x 17014 and ~10000 of Xml objects) the overhead becomes frightening. Removing FullDebug mode returned memory consumption to its normal values.
Hope this help somebody.
consider the next sample application
program TestMemory;
{$APPTYPE CONSOLE}
uses
PsAPI,
Windows,
SysUtils;
function GetUsedMemoryFastMem: cardinal;
var
st: TMemoryManagerState;
sb: TSmallBlockTypeState;
begin
GetMemoryManagerState(st);
result := st.TotalAllocatedMediumBlockSize + st.TotalAllocatedLargeBlockSize;
for sb in st.SmallBlockTypeStates do
begin
result := result + sb.UseableBlockSize * sb.AllocatedBlockCount;
end;
end;
function GetUsedMemoryWindows: longint;
var
ProcessMemoryCounters: TProcessMemoryCounters;
begin
Result:=0;
ProcessMemoryCounters.cb := SizeOf(TProcessMemoryCounters);
if GetProcessMemoryInfo(GetCurrentProcess(), #ProcessMemoryCounters, ProcessMemoryCounters.cb) then
Result:= ProcessMemoryCounters.WorkingSetSize
else
RaiseLastOSError;
end;
procedure Test;
const
Size = 1024*1024;
var
P : Pointer;
begin
GetMem(P,Size);
Writeln('Inside');
Writeln('FastMem '+FormatFloat('#,', GetUsedMemoryFastMem));
Writeln('Windows '+FormatFloat('#,', GetUsedMemoryWindows));
Writeln('');
FreeMem(P);
end;
begin
Writeln('Before');
Writeln('FastMem '+FormatFloat('#,', GetUsedMemoryFastMem));
Writeln('Windows '+FormatFloat('#,', GetUsedMemoryWindows));
Writeln('');
Test;
Writeln('After');
Writeln('FastMem '+FormatFloat('#,', GetUsedMemoryFastMem));
Writeln('Windows '+FormatFloat('#,', GetUsedMemoryWindows));
Writeln('');
Readln;
end.
the results returned by the app are
Before
FastMem 1.844
Windows 3.633.152
Inside
FastMem 1.050.612
Windows 3.637.248
After
FastMem 2.036
Windows 3.633.152
I wanna know why the results of the memory usage are different in the Before and After:
Any memory manager (including FastMM) incurs some overhead, otherwise Delphi could have just used the Windows memory management.
The difference you observe is the overhead:
structures that FastMM uses to keep track of memory usage,
pieces of memory that FastMM did not yet return to the Windows memory management to optimize similar memory allocations in the future.
Because the memory manager is doing clever things in the background to speed up performance.
How does it work getmem/malloc/free?
Heap Allocator - As used by malloc...
1) Internally allocates large chunks(typically 64K up to 1Megabyte) of memory and then sub-divides the chunks up to give you the 100byte and 200byte objects and strings in the program.
When you free memory all that happens is the place where it was allocated from in the internal buffer or chunk is then marked as free. NOTHING ACTUALLY HAPPENS!
2) So you can think of the HEAP as a list of big chunks of memory, and all the objects in your program are just little parts of those chunks.
3) The big internal chunks of memory are only freed when all the objects inside them have been freed, so the usual case is that when you free some object that nothing actually happens except some bits get marked as being available.
That is a fairly naive description of the heap system, but most heaps work in a similar way, but do a lot more optimization than that. But your question is why does the memory not go down and the answer is because nothing actually gets freed. The internal pages of memory are retained for the next call to "new" or "malloc" etc...
PICTURE IT
INSIDE HEAP IS ONE HUGE BLOCK OF 100Kb
You call "malloc(1000)" or "getmem(1000)" to get a 1K block of memory.
Then all that happens is that the 1K block of memory is taken from the 100kb block of memory leaving 99K of memory available in that block. If you keep calling malloc or getmem then it will just keep dividing the larger block up until it needs another larger block.
Each little block of memory allocated with a call to malloc or getmem actually gets about 16 or 24 extra bytes(depending on allocator) extra memory. That memory is bits that the allocator uses to know what is allocated and also where it is allocated.
My application builds many objects in memory based on filenames (among other string based information). I was hoping to optimise memory usage by storing the path and filename separately, and then sharing the path between objects in the same path. I wasn't trying to look at using a string pool or anything, basically my objects are sorted so if I have 10 objects with the same path I want objects 2-10 to have their path "pointed" at object 1's path (eg object[2].Path=object[1].Path);
I have a problem though, I don't believe that my objects are in fact sharing a reference to the same string after I think I am telling them to (by the object[2].Path=object[1].Path assignment).
When I do an experiment with a string list and set all the values to point to the first value in the list I can see the "memory conservation" in action, but when I use objects I see absolutely no change at all, admittedly I am only using task manager (private working set) to watch for memory use changes.
Here's a contrived example, I hope this makes sense.
I have an object:
TfileObject=class(Tobject)
FpathPart: string;
FfilePart: string;
end;
Now I create 1,000,000 instances of the object, using a new string for each one:
var x: integer;
MyFilePath: string;
fo: TfileObject;
begin
for x := 1 to 1000000 do
begin
// create a new string for every iteration of the loop
MyFilePath:=ExtractFilePath(Application.ExeName);
fo:=TfileObject.Create;
fo.FpathPart:=MyFilePath;
FobjectList.Add(fo);
end;
end;
Run this up and task manager says I am using 68MB of memory or something. (Note that if I allocated MyFilePath outside of the loop then I do save memory because of 1 instance of the string, but this is a contrived example and not actually how it would happen in the app).
Now I want to "optimise" my memory usage by making all objects share the same instance of the path string, since it's the same value:
var x: integer;
begin
for x:=1 to FobjectList.Count-1 do
begin
TfileObject(FobjectList[x]).FpathPart:=TfileObject(FobjectList[0]).FpathPart;
end;
end;
Task Manager shows absouletly no change.
However if I do something similar with a TstringList:
var x: integer;
begin
for x := 1 to 1000000 do
begin
FstringList.Add(ExtractFilePath(Application.ExeName));
end;
end;
Task Manager says 60MB memory use.
Now optimise with:
var x: integer;
begin
for x := 1 to FstringList.Count - 1 do
FstringList[x]:=FstringList[0];
end;
Task Manager shows the drop in memory usage that I would expect, now 10MB.
So I seem to be able to share strings in a string list, but not in objects. I am obviously missing something conceptually, in code or both!
I hope this makes sense, I can really see the ability to conserve memory using this technique as I have a lot of objects all with lots of string information, that data is sorted in many different ways and I would like to be able to iterate over this data once it is loaded into memory and free some of that memory back up again by sharing strings in this way.
Thanks in advance for any assistance you can offer.
PS: I am using Delphi 2007 but I have just tested on Delphi 2010 and the results are the same, except that Delphi 2010 uses twice as much memory due to unicode strings...
When your Delphi program allocates and deallocates memory it does this not by using Windows API functions directly, but it goes through the memory manager. What you are observing here is the fact that the memory manager does not release all allocated memory back to the OS when it's no longer needed in your program. It will keep some or all of it allocated for later, to speed up later memory requests in the application. So if you use the system tools the memory will be listed as allocated by the program, but it is not in active use, it is marked as available internally and is stored in lists of usable memory blocks which the MM will use for any further memory allocations in your program, before it goes to the OS and requests more memory.
If you want to really check how any changes to your programs affect the memory consumption you should not rely on external tools, but should use the diagnostics the memory manager provides. Download the full FastMM4 version and use it in your program by putting it as the first unit in the DPR file. You can get detailed information by using the GetMemoryManagerState() function, which will tell you how much small, medium and large memory blocks are used and how much memory is allocated for each block size. For a quick check however (which will be completely sufficient here) you can simply call the GetMemoryManagerUsageSummary() function. It will tell you the total allocated memory, and if you call it you will see that your reassignment of FPathPart does indeed free several MB of memory.
You will observe different behaviour when a TStringList is used, and all strings are added sequentially. Memory for these strings will be allocated from larger blocks, and those blocks will contain nothing else, so they can be released again when the string list elements are freed. If OTOH you create your objects, then the strings will be allocated alternating with other data elements, so freeing them will create empty memory regions in the larger blocks, but the blocks won't be released as they contain still valid memory for other things. You have basically increased memory fragmentation, which could be a problem in itself.
As noted by another answer, memory that is not being used is not always immediately released to the system by the Delphi Memory Manager.
Your code guarantees a large quantity of such memory by dynamically growing the object list.
A TObjectList (in common with a TList and a TStringList) uses an incremental memory allocator. A new instance of one of these containers starts with memory allocated for 4 items (the Capacity). When the number of items added exceeds the Capacity additional memory is allocated, initially by doubling the capacity and then once a certain number of items has been reached, by increasing the capacity by 25%.
Each time the Count exceeds the Capacity, additional memory is allocated, the current memory copied to the new memory and the previously used memory released (it is this memory which is not immediately returned to the system).
When you know how many items are to be loaded into one of these types of list you can avoid this memory re-allocation behaviour (and achieve a significant performance improvement) by pre-allocating the Capacity of the list accordingly.
You do not necessarily have to set the precise capacity needed - a best guess (that is more likely to be nearer, or higher than, the actual figure required is still going to be better than the initial, default capacity of 4 if the number of items is significantly > 64)
Because task manager does not tell you the whole truth. Compare with this code:
var
x: integer;
MyFilePath: string;
fo: TfileObject;
begin
MyFilePath:=ExtractFilePath(Application.ExeName);
for x := 1 to 1000000 do
begin
fo:=TfileObject.Create;
fo.FpathPart:=MyFilePath;
FobjectList.Add(fo);
end;
end;
To share a reference, strings need to be assigned directly and be of the same type (Obviously, you can't share a reference between UnicodeString and AnsiString).
The best way I can think of to achieve what you want is as follow:
var StrReference : TStringlist; //Sorted
function GetStrReference(const S : string) : string;
var idx : Integer;
begin
if not StrReference.Find(S,idx) then
idx := StrReference.Add(S);
Result := StrReference[idx];
end;
procedure YourProc;
var x: integer;
MyFilePath: string;
fo: TfileObject;
begin
for x := 1 to 1000000 do
begin
// create a new string for every iteration of the loop
MyFilePath := GetStrReference(ExtractFilePath(Application.ExeName));
fo := TfileObject.Create;
fo.FpathPart := MyFilePath;
FobjectList.Add(fo);
end;
end;
To make sure it has worked correctly, you can call the StringRefCount(unit system) function. I don't know in which version of delphi that was introduced, so here's the current implementation.
function StringRefCount(const S: UnicodeString): Longint;
begin
Result := Longint(S);
if Result <> 0 then
Result := PLongint(Result - 8)^;
end;
Let me know if it worked as you wanted.
EDIT: If you are afraid of the stringlist growing too big, you can safely scan it periodically and delete from the list any string with a StringRefCount of 1.
The list could be wiped clean too... But that will make the function reserve a new copy of any new string passed to the function.