CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Brendan Tompkins [MVP]

Blog First. Ask Questions Later.

String.Empty vs. ""

So, I just converted a bunch of code that used "" as an empty string like this:

if(myString == "") anotherString = "";

to

if(myString.Equals(String.Empty))  anotherString = String.Empty;

and I'm wondering if I did the right thing, using String.Empty. I hate having quoted strings in code and prefer to stay away from them whenever possible.  This generally leads to code that is more strongly typed, and easier to maintain, so using String.Empty intuitively feels better than ““.   But, I've actually found a concrete reason to use String.Empty - I did some research and found that in a test, str.Equals(String.Empty) is faster than comparing to ""!   Well, okay.  Research isn't the right word, “Doing one google search and accepting on faith the first post I saw” is slightly more accurate.  I even created a little graph of the claims in this post here, that String.Empty is faster.  I'm too lazy to do the test myself, so if you want to verify this, knock yourself out.  I do love making graphs though.

 

 

 

 



Comments

Brendan F Tompkins said:

Yeah. It looks the fastest. I don't know why, but I like using String.Empty better.
# October 14, 2003 9:46 AM

Doug Thews said:

Yes, it is documented that String.Empty is faster. The primary reason is that = "" actually creates an object, leading to more assembly code on the execution stack.

FYI ... Another tip when using strings is to use StringBuilder when concatenating strings.

You can check out a book I co-authored for other ASP.NET performance tips on Amazon.com. Look for "Professional ASP.NET Performance", by Wrox Press.
# October 14, 2003 10:38 AM

Sigurdur G. Gunnarsson said:

Microsoft recommends using "string.Length == 0", there is even a rule to that ends in the latest FxCop versions :)
# October 15, 2003 7:05 AM

Alex said:

Comparing to String.Empty is faster than comparing to "" simply because in "" case compiler has to actually create this empty string and then compare two strings. In case of comparing to String.Empty compiler doesn't create another string, it simply checks the length of the string.
# April 21, 2004 7:29 AM

Edward Burritt said:

I ran an extensive test and determined that the quickest and most efficient way is to use str.Text.Length = 0. Str being the name of the textbox.
# August 4, 2004 7:52 AM

Pepsi Mathew said:

string.Empty is type safe and the code that uses string.Empty will have a professional touch than using "". Using "" is a not a good practice. So do the same thing in a better way. Let's use string.Empty.
# February 25, 2005 3:15 PM

Pepsi Mathew said:

string.Empty is type safe and the code that uses string.Empty will have a professional touch than using "". Using "" is a not a good practice. So do the same thing in a better way. Let's use string.Empty.
# February 25, 2005 3:15 PM

Pepsi Mathew said:

string.Empty is type safe and the code that uses string.Empty will have a professional touch than using "". Using "" is a not a good practice. So do the same thing in a better way. Let's use string.Empty.
# February 25, 2005 3:15 PM

Adi said:

"What about (myString.Length == 0) or (myString.Length < 1)?"

Should be the fastest method. But keep in mind that myString might be null (!).
So, if you want (and you want!) to be 100% safe, you should first compare myString against null.
I don't know how this will affect the graph above, but:

myString == string.Empty

do not need an explicit comparison against null value.

I'm too lazy to find out the difference, I just wanted to point out this little thing.

# June 23, 2005 9:12 AM

jc said:

What are the reasons against just setting the default value to 'null'?
# October 27, 2005 3:01 PM

Royh said:

About checking null value:

http://localhost/t.aspx

string myString = Request["UserName"]; //myString null here.

if(myString == "") anotherString = "DDD";//No error, but anotherString is not "DDD".

if(myString.Equals(String.Empty))  anotherString = String.Empty;//Error!

if(myString.Length==0)  anotherString = String.Empty;//Error!
# June 11, 2006 4:22 AM

wood said:

How about String.IsNullOrEmpty( str ) ?
This is new in .net 2.0
# July 28, 2006 4:10 AM

Derek said:

The .Net FxCop has some prebuilt-in rules for performance. I occassionally run that against my code to clean and speed it up.
# August 19, 2006 1:31 PM

Doug said:

From my tests comparing the string's length to 0 rather than comparing the string to String.Empty was about two times faster in debug mode, and about 16.8 times faster in release mode. I had to iterate 100,000,000 times for each one, so keep in mind that .00016 milliseconds isn't really that much slower than .00001 milliseconds.

The empty string literal was effectively the same speed as String.Empty; however, I would agree with the poster that String.Empty is cleaner since it evaluates properly when comparing against null. That said, I still prefer checking the length to 0. :)

# September 29, 2006 4:21 PM

Doug said:

By the way, when comparing the length to 0, I did check for null first.

# September 29, 2006 4:21 PM

butterflydust said:

Which one is easier to read?  

If it's a distraction to maintenance programmers, that's the real performance cost.

And more time has been spent typing on this blog than the entire aggregated duration of the differences in speed in every single instance that one these calls have ever been made;  in every program and every loop that has used them.  Ever.  Put together.

And you've still got the null check which makes the little difference look like a rounding error.

Use string.IsEmptyOrNull()  for checks.  It is VERY clear and safe.  

Everybody knows what "" means, and its a lot easier to type, but ... string.Empty is OK.

# October 16, 2006 10:37 AM

Jon said:

string.length is the fastest, but only under high iterations.

on my test machine results in ms for 10 million iterations (in milliseconds)

93,110,265,266,47

Here' the code if you want to try it out on your machine.

 {

           string test = "test";

           int j = 0;

           long test1time = 0;

           long test2time = 0;

           long test3time = 0;

           long test4time = 0;

           long test5time = 0;

           long starttime = Environment.TickCount;

           //Test 1 Equals string.Empty

           for (int i = 0; i < 10000000; i++)

           {

               if (test.Equals(string.Empty))

               {

                   j++;

               }

           }

           test1time = Environment.TickCount - starttime;

           //Test 2 Equals ""

           starttime = Environment.TickCount;

           for (int i = 0; i < 10000000; i++)

           {

               if (test.Equals(""))

               {

                   j++;

               }

           }

           test2time = Environment.TickCount - starttime;

           //Test 3 ""

           starttime = Environment.TickCount;

           for (int i = 0; i < 10000000; i++)

           {

               if (test == "")

               {

                   j++;

               }

           }

           test3time = Environment.TickCount - starttime;

           //Test 4 string.empty

           starttime = Environment.TickCount;

           for (int i = 0; i < 10000000; i++)

           {

               if (test == string.Empty)

               {

                   j++;

               }

           }

           test4time = Environment.TickCount - starttime;

           //Test 5 string.length

           starttime = Environment.TickCount;

           for (int i = 0; i < 10000000; i++)

           {

               if (test.Length == 0)

               {

                   j++;

               }

           }

           test5time = Environment.TickCount - starttime;

           //Sjow Results

           string msg = "Test run times (ms) -> Test1,Test2,Test3,Test4,Test5: " + test1time.ToString() + "," + test2time.ToString() + "," + test3time.ToString() + "," + test4time.ToString() + "," + test5time.ToString();

           MessageBox.Show(msg);

       }

# November 29, 2006 3:33 PM

Peter said:

My guess is that because strings are immutable each reference to "" will have a reference to an empty string in a heap. For the first time .NET runtime will allocate ""  string in a heap. Then theoretically GC will collect it and if you reference it again, runtime will have to create another empty string.

Using String.Empty shouldn't create problems with allocating empty string and Garbage Collection. It is also faster because it doesn't reference another string on a heap.

# December 26, 2006 12:14 PM

zongwen啊 said:

啊哈

# May 16, 2007 10:10 PM

Matt said:

"" always creates a new string. string.Empty is a static property on the string object. Using string.Empty avoids the overhead of creating a new string.

# October 3, 2007 2:05 PM

小飞龙 said:

string.Empty不分配存储空间

# November 13, 2007 3:15 AM

Steve said:

I could give a fuck. Boring, stupid, doesnt matter.

# December 13, 2007 11:06 PM

Empty strings | Polymath Programmer said:

Pingback from  Empty strings | Polymath Programmer

# December 31, 2007 6:06 AM

SK said:

不知不觉何时起,开始倾向于在代码中使用String.Empty。今天决定来探究一下

# January 11, 2008 2:28 AM

John Vivian said:

I few things to Note

"" can have Hidden chars your IDE dosent display

I have seen myString == "" fail as the programer cut and pasted code.

The problem was that "".length = 1 so there was a char in the string that is not renderd in the IDE.

String.Empty is a fixed value

String.Empty is defined as

public static readonly string Empty = "";

and

string.Empty.length = 0;

so there are no Hidden chars

This is is One instance of a string common to all .Net lauguages

for comparason to empty and null string.IsNullOrEmpty(myString) is safeist

using reflector the method appers like this

public static bool IsNullOrEmpty(string value)

{

   if (value != null)

   {

       return (value.Length == 0);

   }

   return true;

}

My vote is use string.Empty and string.IsNullOrEmpty.

PS if you find string.Empty harded to understand than "" it is time to give up your day job :P

# February 26, 2008 7:44 AM

HR said:

There is JIT optimization known bug for IsNullOrEmpty. Google on IsNullOrEmpty  and optimization. It is fixed in post Orcas.

connect.microsoft.com/.../ViewFeedback.aspx

I will go for String.Empty right now

# April 5, 2008 9:47 AM

ArunaJyothi said:

Very good Idea. Thanks for an idea.

# October 16, 2008 6:27 AM

Arunajyothi said:

Thanks for good idea

# October 16, 2008 6:29 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About Brendan Tompkins

Brendan has been programming with .NET since the first public beta and is owner and operator of Port Technology Services, a consultancy company providing .NET application development services to the Maritime industry. In July, 2007, he was awarded the Microsoft MVP award for ASP.NET. He's also a proud co-founder of failed .COM startup Intrinsigo, and has had a hand in the failure of numerous other businesses. He currently runs CodeBetter.Com and Devlicio.us, and lives in Norfolk, Virgina with his wife Tiara and son Ian.

View Brendan's profile on LinkedIn

Check out Devlicio.us!

Our Sponsors

Proudly Partnered With


This Blog

Syndication

News

MVP
Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 License.