This section describes how to compare a method of string with an attribute when determining whether a string variable is null. To give a string variable 's', which of the following expressions is faster?
1. String. isnullorempty (s)
2. S = NULL | S. Length = 0
If you guess the second one, you are right. It will be 15% faster than the string. isnullorempty method, but this is measured in one second per million!
Here is a simple example to compare two methods:
Using system;
Namespace stringnullempty
{
Class Program
{
Static void main (string [] ARGs)
{
Long Loop = 100000000;
String S = NULL;
Long option = 0;
Long empties1 = 0;
Long empties2 = 0;
Datetime time1 = datetime. now;
For (long I = 0; I <loop; I ++)
{
Option = I % 4;
Switch (option)
{
Case 0:
S = NULL;
Break;
Case 1:
S = string. empty;
Break;
Case 2:
S = "H ";
Break;
Case 3:
S = "hi ";
Break;
}
If (string. isnullorempty (s ))
Empties1 ++;
}
Datetime time2 = datetime. now;
For (long I = 0; I <loop; I ++)
{
Option = I % 4;
Switch (option)
{
Case 0:
S = NULL;
Break;
Case 1:
S = string. empty;
Break;
Case 2:
S = "H ";
Break;
Case 3:
S = "hi ";
Break;
}
If (S = NULL | S. Length = 0)
Empties2 ++;
}
Datetime time3 = datetime. now;
Timespan span1 = time2.subtract (time1 );
Timespan span2 = time3.subtract (time2 );
Console. writeline ("(string. isnullorempty (s): Time = {0} empties = {1 }",
Span1, empties1 );
Console. writeline ("(S = NULL | S. Length = 0): Time = {0} empties = {1 }",
Span2, empties2 );
Console. Readline ();
}
}
}
The result is as follows:
(String. isnullorempty (s): Time = 00:00:06. 8437500 empties = 50000000
(S = NULL | S. Length = 0): Time = 00:00:05. 9218750 empties = 50000000
Bytes ---------------------------------------------------------------------------------------------
It can be seen that although string. isnullorempty runs slowly, it is easy to read and Microsoft's design is quite user-friendly ~