C # three methods for determining null strings:
String a = "";
1. if (a = "")
2. if (a = String. Empty)
3. if (a. Length = 0)
The three methods are equivalent, so which method has the highest performance? I will illustrate the problem with an experiment.
Create three aspx pages (why use web pages, mainly using Microsoft Application Center Test)
WebForm1.aspx
PrivatevoidPage_Load (objectsender, System. EventArgse)
{
Stringa = "";
For (inti = 0; I <= 1000000; I ++)
{
If (a = "")
{
}
}
}
WebForm2.aspx
PrivatevoidPage_Load (objectsender, System. EventArgse)
{
Stringa = "";
For (inti = 0; I <= 1000000; I ++)
{
If (a = String. Empty)
{
}
}
}
WebForm3.aspx
PrivatevoidPage_Load (objectsender, System. EventArgse)
{
Stringa = "";
For (inti = 0; I <= 1000000; I ++)
{
If (a. Length = 0)
{
}
}
}
Create three stress testing projects under Microsoft Application Center Test:
Test results:
WebForm1.aspx ---------- if (a = "")
WebForm2.aspx ------- if (a = String. Empty)
WebForm3.aspx ------- if (a. Length = 0)
Therefore, the result of quantification in the three methods is 98,105,168:
Method Result
If (a = "") 98
If (a = String. Empty) 105
If (a. Length = 0) 168
So why is if (a. Length = 0) the fastest?
Because integer judgment is the fastest, there is no complicated process such as instantiation.
Therefore, we recommend that you use if (a. Length = 0) to determine whether the string is null ).