开发者

return new string vs .ToString()

开发者 https://www.devze.com 2022-12-26 01:13 出处:网络
Take the following code: public static string ReverseIt(string myString) { char[] foo = myString.ToCharArray();

Take the following code:

    public static string ReverseIt(string myString)
    {
        char[] foo = myString.ToCharArray();
        Array.Reverse(foo);
        return new string(foo);
    }

I understand that strings are immutable, but what I dont understand is why a new string开发者_StackOverflow中文版 needs to be called

return new string(foo);

instead of

return foo.ToString();

I have to assume it has something to do with reassembling the CharArray (but thats just a guess).

Whats the difference between the two and how do you know when to return a new string as opposed to returning a System.String that represents the current object?


Quite simply, because calling ToString() on a char array gives you

System.Char[]

Try

    char[] ca = "Hello world".ToCharArray();
    Console.WriteLine("{0}", ca);

You don't get Hello World

Also calling Array.Reverse to reverse strings is a bad idea, Tony and Jon mention it in their - now famous - Stack Overflow Presentation


The second just calls ToString on an instance of char array, while the first uses a string constructor to obtain a string from a char array. They really have nothing to do with each other.


Here is the IL for the 2 functions:

private string test(String myString){

        char[] foo = myString.ToCharArray(); 
        Array.Reverse(foo); 
        return new string(foo); 
}


test:
IL_0000:  nop         
IL_0001:  ldarg.1     
IL_0002:  callvirt    System.String.ToCharArray
IL_0007:  stloc.0     
IL_0008:  ldloc.0     
IL_0009:  call        System.Array.Reverse
IL_000E:  nop         
IL_000F:  ldloc.0     
IL_0010:  newobj      System.String..ctor
IL_0015:  stloc.1     
IL_0016:  br.s        IL_0018
IL_0018:  ldloc.1     
IL_0019:  ret         


private string tess(String myString)
{

        char[] foo = myString.ToCharArray(); 
        Array.Reverse(foo); 
        return foo.ToString(); 
}

tess:
IL_0000:  nop         
IL_0001:  ldarg.1     
IL_0002:  callvirt    System.String.ToCharArray
IL_0007:  stloc.0     
IL_0008:  ldloc.0     
IL_0009:  call        System.Array.Reverse
IL_000E:  nop         
IL_000F:  ldloc.0     
IL_0010:  callvirt    System.Object.ToString
IL_0015:  stloc.1     
IL_0016:  br.s        IL_0018
IL_0018:  ldloc.1     
IL_0019:  ret         


An array of characters has a speedier/optimized external call to the CLR in the string constructor, so in this case, it's a faster operation.

String has a specific constructor for this:

[MethodImpl(MethodImplOptions.InternalCall)]
public extern String(char[] value);
0

精彩评论

暂无评论...
验证码 换一张
取 消