I'm using them alternately. Is there a difference between them?
-
Related: *[Difference between IEnumerable Count() and Length](https://stackoverflow.com/questions/2521592/difference-between-ienumerable-count-and-length)* – Peter Mortensen Jul 08 '23 at 22:15
4 Answers
On the surface they would seem functionally identical, but the main difference is:
Lengthis a property that is defined of strings and is the usual way to find the length of a string.Count()is implemented as an extension method. That is, whatstring.Count()really does is callEnumerable.Count(this IEnumerable<char>), aSystem.Linqextension method, given thatstringis really a sequence ofchars.
Performance concerns of LINQ enumerable methods notwithstanding, use Length instead, as it's built right into strings.
- 700,868
- 160
- 1,392
- 1,356
String implements the IEnumerable, so it has a method Count while Length is a property in the String class.
- 3,199
- 2
- 21
- 25
String.Length is the "correct" property to use. String.Count() is just an IEnumerable<T>.Count() implementation and could be slower.
- 19,266
- 4
- 41
- 57
I was curious about the speed difference between Count and Length. I believed Length would be faster ...
I created a simple script in LINQPad to test this:
Stopwatch timer = new Stopwatch();
string SomeText = @"";
bool DoLength = true;
//DoLength = false;
if (DoLength) //1252
{
timer.Start();
SomeText.Length.Dump("Length");
timer.Stop();
timer.ElapsedTicks.Dump("Elapsed");
}
else //1166
{
timer.Start();
SomeText.Count().Dump("Count");
timer.Stop();
timer.ElapsedTicks.Dump("Elapsed");
}
I added a long string of text to test this in SomeText. I noted that I had to do them in separate runs to get more accurate results for the second test. Running in tandem always resulted in a faster response on the second call. (Removing the comment for DoLength will run the count test).
I put my results in comments next to the if or else. I was surprised that Count turned out to be faster than Length.
Feel free to do your own tests.
- 30,738
- 21
- 105
- 131
- 62
- 4