Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
650 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...