Today browse
DevTopics
when the blog, found an introductory essay String, is whether the introduction is empty, a comparison between the methods of the String property and a judge a String variable to a string variable 's', the following expression type faster?
Here's a simple example to compare two ways :
1. String.IsNullOrEmpty( s )
2. s == null || s.Length == 0
If you guessed the second one, then you're right. It String.IsNullOrEmpty 15% faster than the method, but this is to be measured in millionths of a second!
2. s == null || s.Length == 0
Here's a simple example to compare two 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();
}
}
}
下面是结果:
(String.IsNullOrEmpty( s )): Time=00:00:06.8437500 Empties=50000000
(s == null || s.Length == 0): Time=00:00:05.9218750 Empties=50000000
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();
}
}
}
下面是结果:
(String.IsNullOrEmpty( s )): Time=00:00:06.8437500 Empties=50000000
(s == null || s.Length == 0): Time=00:00:05.9218750 Empties=50000000
Reproduced in: https: //www.cnblogs.com/yangjie5188/archive/2008/02/21/1076767.html