string.Empty vs null.Which one do you use?

user712923 picture user712923 · Jul 14, 2011 · Viewed 63.7k times · Source

Recently a colleague at work told me not to use string.Empty when setting a string variable but use null as it pollutes the stack?

He says don't do

string myString=string.Empty; but do string mystring=null;

Does it really matter? I know string is an object so it sort of makes sense.

I know is a silly question but what is your view?

Answer

Marc Gravell picture Marc Gravell · Jul 14, 2011

null and Empty are very different, and I don't suggest arbitrarily switching between them. But neither has any extra "cost", since Empty is a single fixed reference (you can use it any number of times).

There is no "pollution" on the stack caused by a ldsfld - that concern is.... crazy. Loading a null is arguably marginally cheaper, but could cause null-reference exceptions if you aren't careful about checking the value.

Personally, I use neither... If I want an empty string I use "" - simple and obvious. Interning means this also has no per-usage overhead.


At the IL level, the difference here between "" and Empty is just ldstr vs ldsfld - but both give the same single interned string reference. Furthermore, in more recent .NET versions the JIT has direct interception of these, yielding the empty string reference without actually doing a static field lookup. Basically, there is exactly no reason to care either way, except readability. I just use "".