12

I'm using them alternately. Is there a difference between them?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Patryk
  • 3,042
  • 11
  • 41
  • 83
  • 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 Answers4

19

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 chars.

Performance concerns of LINQ enumerable methods notwithstanding, use Length instead, as it's built right into strings.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
2

String implements the IEnumerable, so it has a method Count while Length is a property in the String class.

abhinav
  • 3,199
  • 2
  • 21
  • 25
2

String.Length is the "correct" property to use. String.Count() is just an IEnumerable<T>.Count() implementation and could be slower.

itsme86
  • 19,266
  • 4
  • 41
  • 57
1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Brad
  • 62
  • 4