is to tell if a string variable is empty, a comparison between a method of string and an attribute, give a string variable ' s ', and the following expression is faster?
1. String.IsNullOrEmpty (s)
2. S = = NULL | | S.length = = 0
If you guess the second one, then you're right. It will be 15% faster than the String.IsNullOrEmpty method, but this is also measured in one out of 10,000 seconds!
Here's a simple example to compare 2 different ways:
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 ();
}
}
}
Here's the result:
(String.IsNullOrEmpty (s)): time=00:00:06.8437500 empties=50000000
(s = = NULL | | s.length = = 0): time=00:00:05.9218750 empties=50000000
---------------------------------------------------------------------------------------------
It can be seen that although the string.isnullorempty run relatively slow, but it is easy to read, Microsoft's design is quite humane ~