What is the difference between String.Count and String.Length?

I use them one at a time, is there any difference between them?

+7
source share
5 answers

On the surface, they seem to be functionally identical, but the main difference is as follows:

  • Length is a property that is defined in strings and is the usual way to find the length of a string.

  • .Count() is implemented as an extension method. What string.Count() really does is call Enumerable.Count(this IEnumerable<char>) , a System.Linq extension method, given that string is really a char s sequence.

Despite the performance problems associated with LINQ enumerated methods, use Length instead, since it is embedded directly in strings.

+12
source

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

+1
source

String.Length is the correct property. String.Count() is just an implementation of IEnumerable<T>.Count() and can be slower.

+1
source

I was interested to know about the speed difference between Count and Length. I thought the length would be faster ...

In LinqPad, I created a simple script 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 line of text to check this in SomeText. I noted that I had to do them in separate runs in order to get more accurate results for the second test. Running in tandem always led to a faster response to the second call. (Removing the comment for DoLength will run the count test).

I put my results in a comment next to if or else. I was surprised that the count was faster than the length.

Feel free to do your own tests.

+1
source

It is related and can answer your question. You should select one and stick to it (probably the length in the case of a simple string)

0
source

All Articles