I have a string that may have whitespace characters around it and I want to check to see whether it is essentially empty.
There are quite a few ways to do this:
1 if (myString.Trim().Length == 0)
2 if (myString.Trim() == "")
3 if (myString.Trim().Equals(""))
4 if (myString.Trim() == String.Empty)
5 if (myString.Trim().Equals(String.Empty))
I'm aware that this would usually be a clear case of premature optimization, but I'm curious and there's a chance that this will be done enough to have a performance impact.
So which of these is the most efficient method?
Are there any better methods I haven't thought of?
Edit: Notes for visitors to this question:
There have been some amazingly detailed investigations into this question - particularly from Andy and Jon Skeet.
If you've stumbled across the question while searching for something, it's well worth your while reading at least Andy's and Jon's posts in their entirety.
It seems that there are a few very efficient methods and the most efficient depends on the contents of the strings I need to deal with.
If I can't predict the strings (which I can't in my case), Jon's IsEmptyOrWhiteSpace
methods seem to be faster generally.
Thanks all for your input. I'm going to select Andy's answer as the "correct" one simply because he deserves the reputation boost for the effort he put in and Jon has like eleventy-billion reputation already.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…