:: KBs ::

Determining if a String is an Empty String

Created Date: 4/23/2008
Last Modified Date: 4/23/2008
In order to test to see if a string has a value there are a couple of different items that can be used to test for empty string:

- value = String.Empty
- value = “”
- value.Length == 0

Which one of these is fastest? The String.Empty and “” requires both objects to be tested for values. The value.Length only has to check to see what the total number of characters.

public void HasValue1()
{
   int Loops = 1000000;

   DateTime StartTime = DateTime.Now;
   for (int i = 0; i < Loops; i++)
   {
      String value = "aa";
      bool isempty;
      isempty = (value == String.Empty);
   }
   DateTime Endtime = DateTime.Now;

   System.Console.WriteLine("value == String.Empty - \t" + Endtime.Subtract(StartTime).TotalSeconds.ToString());
}

public void HasValue2()
{
   int Loops = 1000000;

   DateTime StartTime = DateTime.Now;
   for (int i = 0; i < Loops; i++)
   {
      String value = "aa";
      bool isempty;
      isempty = (value == "");
   }
   DateTime Endtime = DateTime.Now;

   System.Console.WriteLine("value == '' - \t" + Endtime.Subtract(StartTime).TotalSeconds.ToString());
}

public void HasValue3()
{
   int Loops = 1000000;

   DateTime StartTime = DateTime.Now;
   for (int i = 0; i < Loops; i++)
   {
      String value = "aa";
      bool isempty;
      isempty = (value.Length == 0);
   }
   DateTime Endtime = DateTime.Now;

   System.Console.WriteLine("value.Length == 0 - \t" + Endtime.Subtract(StartTime).TotalSeconds.ToString());
}


















1000000 Loops (in Sec)
value == String.Empty 0.0625
value == '' 0.0625
value.Length == 0 0.015625

:: Better Coding Practices ::