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.
Brad
source share