开发者

How much space do string.Empty and null take?

How much memory do an empty string and null take?

I found th开发者_StackOverflow中文版is 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);
    }


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


Both the same, I guess. One is the null reference (i.e. likely some magic internal reference value reserved for null) and one is a reference to a static field in a class. I doubt they'll be different memory-wise. Note: This is a guess, not knowledge, but whatever the actual answer is, I doubt you'll see big differences. Expect them in the range of a few bytes, if that much at all.

In any case, why are you worrying about this instead of using your time to solve actual, interesting or important problems?


If you want to do something like free the space used by the string, and it doesn't matter which one you pick, use null. It could save memory, possibly (doubtful though since String.Empty is pooled) but it doesn't really matter. null is correct.


Go with null if you want the data to literally represent nothing. Go with string.empty if you literally want the string to be empty (ie if you want to manipulate that empty string later on). Memory should not be the issue at hand here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜