Today, when browsing the devtopics blog, I found an article about string, which 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