Convert char array to string

23 Oct 2016

C# language provides various ways to construct a string from the character array. Things seems easy which way you prefer, but performance differs a lot.

Method 1 :

Due to influence from the loosely typed language(JavaScript), I tried out static Join method from string class.

It looked supper simple, but while solving a programming problem with 1000000 characters array, I realized it is too slow due to multiple strings that are created in forming a complete string.

char[] array = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 
's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

Console.WriteLine(string.Join("", array));

Method 2 :

Using string builder, we can loop through the given char array and create a string as follows. This method is preferred comparing to the first one because this does involve a single string object creation.

char[] array = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 
's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

StringBuilder sb = new StringBuilder();

foreach(var c in array)
 sb.Append(c);

Console.WriteLine(sb.ToString());

Method 3 :

Then I found out a most basic thing that I should have done in the first place. Following is the most effective way to create a string from char[].

char[] array = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 
's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

Console.WriteLine(new string(array));

In most cases, we won't see a big difference. but knowing the difference helps you a lot when it is required (Like in my caseembarassed).