The three methods are as follows:
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
Copy codeThe Code is as follows:
Private void Page_Load (object sender, System. EventArgs e)
{
String a = "";
For (int I = 0; I <= 1000000; I ++)
{
If (a = "")
{
}
}
}
WebForm2.aspx
Copy codeThe Code is as follows:
Private void Page_Load (object sender, System. EventArgs e)
{
String a = "";
For (int I = 0; I <= 1000000; I ++)
{
If (a = String. Empty)
{
}
}
}
WebForm3.aspx
Copy codeThe Code is as follows:
Private void Page_Load (object sender, System. EventArgs e)
{
String a = "";
For (int I = 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?If (a. Length = 0) is the fastestWhat about it?
Because integer judgment is the fastest, there is no complicated process such as instantiation.
Therefore, it is recommended that you determine whether the string is null.If (a. Length = 0 ).