问题
How can I best determine the Size of a Class from Memory?
Here is a basic sample class to work with - Note the variables serve no purpose other than for the example:
type
TMyClass = class
public
fString1: string;
fString2: string;
fInteger1: Integer;
fInteger2: Integer;
constructor Create;
destructor Destroy; override;
end;
What I would like to do is return the same size as if it were a file on disk.
So if I saved TMyClass to File and the Size of the File was 2.4kb for example, I would like to get that value without even needing the File to be on disk (getting the size from Memory).
I have been searching and reading before asking here, this is what I have tried so far with mixed results:
InstanceSize
Using TMyClass.InstanceSize on my class only ever returns the value 12.
SizeOf
Using SizeOf(TMyClass) on my class only ever returns the value 4.
Whatever the values return I will be formatting to FileSize format such as kilobytes and megabytes etc.
I must be doing something wrong because I know for a fact there is more than 12 (or 4) bytes of data being used on my class. I also know I am referencing the correct class, it is the same class I am creating and freeing in the Form Create and Destroy events - as well as using at runtime.
Is what I am trying to do the correct way to go about it, and if so should my examples work? If they should work, I know then I need to look closer at my actual classes and objects.
The dirty way to achieve this would be for me to save my object classes to file, read the file size and then delete the temp file. But I don't like doing approaches like that, I think they are dirty and taking shortcuts. The purpose is to read the size of my classes from memory, without resorting to saving and temp files etc.
I look forward to hearing your advice and suggestions thanks.
回答1:
Not sure how you got 12 for your InstanceSize
on a class like that. It should be 20 (pre-D2009) or 24 (D2009 and later). The reason it's so much smaller than the actual size of your saved file is because the strings aren't held in the object itself; they're reference types, implemented as pointers to the actual string data.
Your "dirty approach" is on the right track. Pretty much the only way to find out how much disk space you need for an object like that is to actually serialize it. But you don't need to save it to disk. If you're currently saving the object with a TFileStream, (and you should be if you're not,) use a TMemoryStream instead, which will "save" it to a memory buffer. Then get the Size
of the stream and that's the serialized size of your object, all without having to create and then delete a temp file.
来源:https://stackoverflow.com/questions/8782518/getting-the-size-of-a-class-or-object-in-the-same-format-as-a-file-size