j_ruez said:
I am trying to learn the best ways to do some things in c#
When testing for an empty string, what is the best way to test it.
For example, if I have a textbox named txtValue
Should I use
txtValue.Text == ""
or
txtValue.Length == 0
and why would I use one over the other. And if it doesn't matter,
just let me know that also.
Thanks
Let's look at the IL:
(txtValue.Text == "") boils down to a call to String.op_Equality(),
which in turn calls String.Equals( string, string). This checks for
reference equality and does some checks for null parameters before
calling String.Equals( string), which is implemented in native code, not
IL, and ILDASM won't tell me what's in there. I decided I didn't need to
go any further (farther?). I'll assume that the first thing
String.Equals does is check for the lengths being the same; actually it
probably checks for reference equality and/or a null parameter first.
(txtValue.Length == 0) boils down to a call to
String.get_Length(), followed by a test for 0 (generally a 'brtrue' IL
instruction).
So, the second idiom is certainly more efficient in terms of IL - but,
we're looking at IL which may well be JIT'ed to some very efficient code
(in both cases), since the String class is sealed.
My opinion (for what it's worth) is to use whichever idiom seems most
readable to you, which may well be different in different areas of code.
I think the real-world speed difference will never be noticed (or even
measurable) in code that's doing any real work with strings.
Also, I'd suggest not using String.Empty (which I've seen in other
responses) - it buys you nothing, and I find it to be far less readable
than the simple, natural, well-used "".