TheDeveloperBlog.com


C# Char Array Use

Char array. A char array stores string data. It is an alternative to using StringBuilder for creating string data quickly. We evaluate a solution using StringBuilder and compare it to an approach that uses character arrays.


Example. First we declare and assign the elements in new char array references. When you use the new operator to create a new char array, the execution engine in the Common Language Runtime allocates memory on the managed heap.

Note: Array elements are stored together in one block of memory. This reduces the overhead with storing separate objects.

And: Char is a value type so the value itself, not a reference, is stored in the storage location.

Char
C# program that declares char arrays

using System;

class Program
{
    static void Main()
    {
	char[] array1 = { 's', 'a', 'm' };
	char[] array2 = new char[] { 's', 'a', 'm' };
	char[] array3 = new char[3];
	array3[0] = 's';
	array3[1] = 'a';
	array3[2] = 'm';
	// Write total length:
	Console.WriteLine(array1.Length + array2.Length + array3.Length);
    }
}

Output

9


Example 2. Here we see that character arrays can be used to store character data such as letters or numbers. Here we append characters one-by-one to an array using the char data type. Remember that chars in the C# language are 2 bytes.

Next: Here is some example code where we replace StringBuilder with a char array. This often improves performance.

Example using char array, fast: C#

class Program
{
    static void Main()
    {
	// Use a new char array.
	char[] buffer = new char[100];
	for (int i = 0; i < 100; i++)
	{
	    buffer[i] = 'a';
	}
	string result = new string(buffer);
    }
}

Example using StringBuilder, slow: C#

using System.Text;

class Program
{
    static void Main()
    {
	// Declare new StringBuilder and append to it 100 times.
	StringBuilder builder = new StringBuilder(100);
	for (int i = 0; i < 100; i++)
	{
	    builder.Append('a');
	}
	string result = builder.ToString();
    }
}

Results

Char[] buffer:   255 ms [faster]
StringBuilder:  1804 ms
Notes:          Filling a buffer of characters if faster.
		Using StringBuilder is slower.

The first method uses char[]. The array is instantiated with the new char syntax, and this allocates 100 2-byte chars. We assign each index to the char we want to append. This example uses the new string constructor.

String Constructor

Tip: The biggest advantage the StringBuilder method has is that you could keep appending items to the buffer after the 100th char.

StringBuilder

Benchmark. Char arrays are faster because they don't have as many features. StringBuilder handles many cases and has many methods. It is easy to use and a great optimization, but it is far slower in simple cases. This can help in real programs.

Note: I used char arrays as an improvement in the alphanumeric sorting algorithm. This improved performance.

Alphanumeric Sorting

Result: Char arrays can be around seven times faster on certain tasks. Char buffers have a big performance advantage.


Discussion. Using char arrays allows you to use more lower-level algorithms with greater performance. The char array code forces me to have more "coding discipline." It is more exact if you can enforce the constraints of char arrays.

Note: StringBuilder could have extra chars appended, but the char array wouldn't allow that.

Therefore: The IndexOutOfRangeException that would be thrown is useful for debugging the algorithm.

IndexOutOfRangeException

Summary. We saw that using char arrays is better when you know in advance the number of characters. StringBuilder is fast and useful, but using char arrays is sometimes more appropriate. Using an array may also encourage higher-quality code.

Review: We considered the differences between character arrays and collection-based methods for storing text data.