During my .NET years I've been many times asked about the differences between C# String.Empty and empty literal (""). Which one is more preferable?! Even when developing C# and .NET coding-style and implementation guidelines this has always been challenging as every programmer has his own ideas and experience.
A)
string s1 = String.Empty;
B)
string s2 = ""; Here is some advise:
Performance
String.Empty is a static read-only public field which is initialised by the static constructor of the String class. Simplified MSIL code generated for A is ldsfld String.Empty which simply pushes the reference of the specified field into local stack after executing class's static constructor for the first time - 5 bytes instruction. Please consider String.Empty assigns the empty literal ("") to a static field only once during the first access to the String class and that's totally not a big deal; the resulting reference to "" will be reused during your application domain lifetime.
At the other hand, the C# statement B results into ldstr "" MSIL statement; again a 5 bytes instruction. ldstr pushes the supplied literal into AppDomain's internal string pool (CLR internal GlobalStringLiteralMap C++ class) if not previously loaded into the map. The reason is obvious, more efficient memory usage by sharing string literals in memory - a technique called string interning.
When comparing the two alternatives, statement A is so straightforward in CLR implementation making it simple and fast, whilst statement B goes through the overhead of checking the AppDomain's string pool (an internal hash-table) bringing very small performance penalties during JIT compilation of the containing method.
Coding Style
Throughout my professional career and when developing proper coding-style, I've considered we're not only talking about technology; it always involves aesthetics and human nature!!! Increasing readability reducing maintenance cost is a generally accepted coding-style design measure.
Picking String.Empty syntax usually results into higher readability score compared to the "" syntax. I'll definitely go for the first one as feel more comfortable when reading and skimming the code, not to mention how error-prone could the latter be when confused with " " (single white-space string literal).
Labels: .NET, C-Sharp, CLR, Microsoft