Can C # get the amount of memory that an object occupies?

Source: Internet
Author: User
Tags int size
Today, when a project is refactored, it suddenly comes to the question of which members of a class will increase, affecting the size of the memory that a class occupies. C # There is no way to know how much memory an object.

First question: Quickly think of a non-static field, attribute of a class.

The second question: the first thought is sizeof ().

The following starts with validation, first verifying the value type, and validating the code as follows:

int size = sizeof (int); 4 bytes

Note point: thesizeof operator applies only to value types, not to reference types. The sizeof operator can only be used in unsafe blocks of code. As the following code will not compile through:

public struct teststuct
    {

    }

int size = sizeof (new teststuct ());

After compiling, prompt:

Error 1 "consoleapplication3.teststuct" does not have a predefined size, so sizeof can only be used in unsafe contexts (consider using SYSTEM.RUNTIME.INTEROPSERVICES.MARSHAL.SIZEOF)

Modified to the Marshal.SizeOf method, the method returns the unmanaged size of the object in bytes. The parameter can be a reference type or a boxed value type. The layout must be continuous or explicit.

int size = marshal.sizeof (new teststuct ()); 1 bytes

Next, verify the reference type:

Cannot compute a meaningful size or offset because it cannot be marshaled as an unmanaged structure. All the following code throws an exception when it is running.

public class Student
    {
    }

 int size = marshal.sizeof (new Student ());

You need to give the student class, plus a structlayoutattribute, to control the physical layout of the data fields of the student class. Modify the code as:

[StructLayout (layoutkind.sequential)]
    public class Student
    {
    }

int size = marshal.sizeof (new Student ());//1 bytes

LayoutKind The default value is auto.

Conclusion:
1: There is no way to directly acquire the memory size of an object for a managed object.
2: Unmanaged object, you can use the marshal.sizeof
3: Use sizeof for built-in types, such as Int,long,byte

Extended:
It was proposed that binary serialization be used to serialize an object into a MemoryStream and then return memorystream.length, which is not validated.

The validation code is as follows:

[Serializable]
 public class Student
    {
    }

private static long Getobjectsize (object o)
        {
            using (var stream = new Memory Stream ())
            {
                var formatter = new BinaryFormatter ();
                Formatter. Serialize (Stream, O);
                using (var fileStream = new FileStream (@ "D:\Student.txt", FileMode.OpenOrCreate, FileAccess.Write))
                {
                    var Buffer = stream. ToArray ();
                    FileStream.Write (buffer, 0, buffer. Length);
                    Filestream.flush ();
                }

                return stream. Length;
            }
        }

 var student = new Student ();
 Long size = getobjectsize (student);  139 bytes

Student.txt saved text information as shown below, through the text information, you can learn more than 100 bytes, it is estimated that this string of strings.

              JConsoleApplication3, version=1.0.0.0, culture=neutral, Publickeytoken=null   Consoleapplication3.student       

Extended reading:
http://blogs.msdn.com/b/cbrumme/archive/2003/04/15/51326.aspx The

original text as follows:

We don ' t expose the managed size of objects because we want to reserve the ability to change the way we lay these things O  Ut.  For example, on some systems we might align and pack differently.  For this to happen, your need to specify Tdautolayout for the layout mask of your valuetype or Class. If you are specify Tdexplicitlayout or Tdsequentiallayout, the CLR ' s freedom to optimize your are layout.

If you are are curious to know the How-a object happens to is, there are a variety of ways to discover this.  Can look in the debugger.  For example, Strike or SOS (son-of-strike) shows you with objects are out. Or you could allocate two objects and then use unverifiable operations to subtract the addresses.  99.9% of the time, the two objects would be adjacent. You can also the use a managed profiler to get a sense of how much memory are consumed by instances of a particular type.

But we don ' t want to provide an API, because then your could form a dependency over this implementation detail.

The

Some people have confused the System.Runtime.InteropServices.Marshal.SizeOf () service with this api. however, Marshal.SizeOf reveals the size of the it has been marshaled.  in other words, it yields the size of The object when converted to a unmanaged Representation.  these sizes'll certainly differ if the CLR ' s Loade R has re-ordered small fields so they can is packed together on a tdautolayout type.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.