Reputation: 3152
I'm using them alternately. Is there a difference between them?
Upvotes: 13
Views: 13356
Reputation: 62
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.
Upvotes: 1
Reputation: 724532
On the surface they would seem functionally identical, but the main difference is:
Length
is 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, what string.Count()
really does is call Enumerable.Count(this IEnumerable<char>)
, a System.Linq
extension method, given that string
is really a sequence of char
s.
Performance concerns of LINQ enumerable methods notwithstanding, use Length
instead, as it's built right into strings.
Upvotes: 20
Reputation: 19526
String.Length
is the "correct" property to use. String.Count()
is just an IEnumerable<T>.Count()
implementation and could be slower.
Upvotes: 2
Reputation: 3217
String implements the IEnumerable
, so it has a method Count
while Length
is a property in the String class.
Upvotes: 2