Why it is preferable to use String.Empty in C# and therefore a public constant in other languages, is that constants are static, therefore only take up one instance in memory.
Every time you do something like this: -
stringVariable = "";
you are creating a new instance of a null string, and pointing to it with stringVariable.
So every time you make an assignment of "" to a variable (pointer), that "" null string is a new string instance until it no longer has any pointer assignments to it.
initializing strings by pointing them all to the same constant, means only one "" is ever created and every initialized variable points to the same null string.
It may sound trivial, but creating and destroying strings is much more resource intensive than creating pointers (variables) and pointing them to an existing string.
As string initialization is common, it is good practice to do: -
const String EMPTY_STRING = "";
String variable1 = EMPTY_STRING;
String variable2 = EMPTY_STRING;
String variable3 = EMPTY_STRING;
String variable4 = EMPTY_STRING;
String variable5 = EMPTY_STRING;
You have created 5 string pointers but only 1 string
rather than: -
String variable1 = "";
String variable2 = "";
String variable3 = "";
String variable4 = "";
String variable5 = "";
You have created 5 string pointers and 5 separate null strings.
Not a major issue in this case, but in thousands of lines of code in dozens of classes, it is unnecessary memory waste and processor use, creating another null string variable, when they can all point to the same one, making applications much more efficient.
Of course, compilers should be clever enough to determine several static strings and reuse duplicates, but why assume?
Also, it's less prone to introducing errors as "" and " " will both compile, yet you may miss the space you accidentally added which could produce spurious run time errors, for example conditional logic such as: -
myvariable = " ";
While (myVariable == ""){
...
}
Code inside the while block is unreachable because myVariable will not satisfy the condition on the first iteration. The error of initializing with " " instead of "" is easy to miss, whereas: -
myvariable = EMPTY_STRING;
While (myVariable == EMPTY_STRING){
...
}
... is less likely to cause runtime errors, especially as misspelling EMPTY_STRING would generate a compile error instead of having to catch the error at run time.
The cleanest solution, would be to create a static class that contains members of all kinds of string constants you need, should you require more than just an empty string.
public static class StringConstants{
public static String Empty = "";
public static String EMail = "mailto:%s";
public static String http = "http://%s";
public static String https = "https://%s";
public static String LogEntry = "TimeStamp:%tYmdHMSL | LogLevel:%s| Type:%s | Message: '%s'";
}
String myVariable = StringConstants.Empty;
You may even be able to extend the native String object, depending on your language.