Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory consumption by Static and Const fields

Tags:

c#

I have a class in which I have a string field. This string field is constant and it will be moved in resource file in future but for the time being it will remain in our class. Now the scenario is that I am making more than hundred's of object of this class. So my question is in which approach less memory will be consumed and why?

  1. I should make my string variable static

    public class MyClass
    {
        public static string MyString = "My String";
    }
    
  2. I should make my string variable const

     public class MyClass
     {
        public const string MyString = "My String";
     }
    
like image 805
Mohd Ahmed Avatar asked Oct 03 '22 16:10

Mohd Ahmed


1 Answers

There is a difference. Static variables are initialized in the dynamic memory space and therefore occupy additional memory space not to mention the fact that you need executable code (additional memory) to initialize them and access them.

All const data is located in the same memory space as executable code which is read-only-memory (ROM), where as static data is loaded into dynamic memory where you can potentially read and write to it. Now here is the interesting part that seems to have been overlooked in previous answers. Static data occupies dynamic memory space but requires additional ROM space and, in the worse case scenario, can take up twice the amount of memory. Consider the following:

class StaticData
{
    static string s_static1 = "My string data";
}

class ConstData
{
    const string CONST1 = "My string data";
}

The class StaticData has variable s_static1 which will occupy dynamic memory space of a single pointer (normally 1 integer). However it also has to be initialized and therefore there must also exist ROM code to initialize it. The string data itself would normally be located in ROM space, since string data is immutable, and would not take up any more space than the constant excample.

For the class ConstData there is only ROM storage space required and therefore this is, in most cases, the best usage of memory.

Now it gets more interesting when you consider how the data is used by the compiler. With the exception of string/character data, constants are normally substituted directly in code at the point of reference. In other words the constant value is directly loaded into a register or pushed onto the stack, depending on usage. In the case of a static variable the compiler has to read that value out of memory via additional code (pointer referencing) and therefore additional ROM code is required.

In summary static code will take up more memory both by occupying additional dynamic memory space and the additional executable code space required to de-referrence it.

like image 118
Donald Fraser Avatar answered Oct 08 '22 01:10

Donald Fraser