Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much space do string.Empty and null take?

Tags:

c#

.net

How much memory do an empty string and null take?

I found this question, which tells about the String.Empty memory allocation but not null.

If I want to store an empty string or null in session which one would take less space?

    class MyClass
    {
        public string One { get; set; }
        public string Two { get; set; }            

        public MyClass(string one,string two)
        {
            One = one;
            Two = two;
        }
    } 
    class Main
    {
       var emp = new MyClass(String.Empty, String.Empty);
       var nul = new MyClass(null,null);
    }
like image 721
Mangesh Pimpalkar Avatar asked Dec 01 '22 08:12

Mangesh Pimpalkar


1 Answers

Within MyClass, there'll be absolutely no difference. Both will be "the size of a reference" - either 4 bytes or 8 bytes. It would also take the same amount of space if the values referred to any other strings.

Of course the empty string object takes up space, but it takes up that the same amount of space however many other references there are to it. (In other words, whether you refer to it or not will make no difference to memory... the string.Empty field will still refer to it, so it's not like it can ever be garbage collected.)

like image 197
Jon Skeet Avatar answered Dec 02 '22 20:12

Jon Skeet