C# Char Array Use

Char type

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.

This C# article shows how to use char arrays. It provides benchmarks.

Declare character arrays

Note

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 where the array elements are stored together in one block of memory. The char data type is a value type so the value is stored in the storage location. This example allocates three character arrays.

Program that declares char arrays [C#]

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

Assign char arrays

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, which is larger than in C and C++, but still small. Here is some example code where we replace StringBuilder with a char[] array.

Example using char array: faster [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: slower [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.

Overview. 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. The second method uses StringBuilder. The biggest advantage the StringBuilder method has is that you could keep appending items to the buffer after the 100th char.

String Constructor

Benchmark

Performance optimization

Char arrays are faster because they don't have as many features. StringBuilder can deal with tons of stuff 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; for example, I used this approach when using GZipStream compression in the C# language. I also used it as an improvement in the alphanumeric sorting algorithm.

Alphanumeric Sorting

Benchmark results. Char arrays can be around seven times faster on certain tasks. I found that avoiding StringBuilder and using char buffers has a big performance advantage. Here we see the performance benchmarks. See the figures above in this article.

Another benefit

Programming tip

From my perspective, 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. StringBuilder could have extra chars appended, but the char array wouldn't allow that. The IndexOutOfRangeException that would be thrown is actually useful for debugging the algorithm.

Summary

Array type

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. This article is helpful when considering the differences between character arrays and collection-based methods for storing text data.

Char Type Array Types
.NET