Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

c# - How much space do string.Empty and null take?

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...