Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.Length vs string.ToCharArray().Length

Tags:

string

c#

I'm cleaning up some old code that's repeatedly doing myString.ToCharArray().Length; instead of myString.Length.

Before I refactor ToCharArray() out, are there any circumstances where doing so would result in different behavior?

like image 616
Dan Is Fiddling By Firelight Avatar asked Mar 22 '13 15:03

Dan Is Fiddling By Firelight


3 Answers

No difference : have a look the method code with reflector : it will allocate a char[] based on the length of the string.

like image 122
mathieu Avatar answered Sep 19 '22 10:09

mathieu


Both will definitely return the same length, representing the number of characters (chars). There'll be one char per each index of the string (or array), and, then, the following could be worthy of mention:

The Length property returns the number of Char objects in this instance, not the number of Unicode characters. The reason is that a Unicode character might be represented by more than one Char. Use the System.Globalization.StringInfo class to work with each Unicode character instead of each Char.

From this you can also deduce that ToCharArray, given that it is "A Unicode character array whose elements are the individual characters of this instance", that they behave the same.

I'm not sure what the not on NullReferenceException is about, as both are susceptible to that, too.

like image 36
Grant Thomas Avatar answered Sep 22 '22 10:09

Grant Thomas


result in different behavior?

Well, as others said, in both ways, result will be the number of char, so, the answer is definitly NO!

But I want to add something different to this answer.

When I decompile String.ToCharArray() method, it looks like:

public unsafe char[] ToCharArray()
{
  int length = this.Length;
  char[] chArray = new char[length];
  if (length > 0)
  {
    fixed (char* smem = &this.m_firstChar)
      fixed (char* dmem = chArray)
        string.wstrcpyPtrAligned(dmem, smem, length);
  }
  return chArray;
}

ToCharArray uses unsafe code that manipulates pointers, along with the private wstrcpyPtrAligned method in the base class library. It is normally faster than doing the same thing in managed code, which has to check array bounds.

But

It makes a complete pass over the string, so if you do not require that, filling character arrays manually may be faster.

Since ToCharArray() method returns a char array, which you can modify in-place. This sometimes improves the performance of code.

like image 40
Soner Gönül Avatar answered Sep 21 '22 10:09

Soner Gönül