Test on memory usage of C # object

Source: Internet
Author: User

In objects, we usually use static members or static methods. Some people say that static methods are used in applications.ProgramOnce started, it will be loaded into the memory, which will speed up the running of the program. In the end, it occupies no memory of the object.
Object
[Serializable]
Public class userinfo
{
}
Test Method
Userinfo user = new userinfo ();
Memorystream MS = new memorystream ();
Binaryformatter formatter = new binaryformatter ();
Formatter. serialize (MS, user );
Ms. Position = 0;
Console. Write (Ms. Length );
An object with no content occupies 118 bytes of memory.
Add two static members to the object class
Static int A = 0;
Static int B = 1;
After the test, it is found that it still occupies 118 bytes, indicating that static members do not occupy the object's memory space.
Add two static methods to the object class
Public static void get ()
{
}
Public static string getstr ()
{
Return "";
}
It is found that the test program still occupies 118 bytes, indicating that the static method does not occupy the object memory.
If you change the static method to a non-static method, it still occupies 118 bytes after running the test program. This means that the non-static method class does not occupy the memory space of the object.
However, when I define two non-static members in the object class
Int AA = 0;
String STR = "DDD ";
After the test is run, it is found that 141 memory bytes are occupied, and non-static variables occupy the memory space of the object.

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.