C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: Array elements are stored together in one block of memory. This reduces the overhead with storing separate objects.
ObjectAnd: Char is a value type so the value itself, not a reference, is stored in the storage location.
CharC# 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
Note: Remember that chars in the C# language are 2 bytes. So for each char, 2 bytes are copied on the stack.
Version 1: This version uses a char array. We assign each index to the char we want to append. We use the string constructor.
String ConstructorVersion 2: We use StringBuilder here. With StringBuilder, you could keep appending items to the buffer after the 100th char.
Result: Using a char array is much faster than the StringBuilder. Internally, the StringBuilder has more branches so is slower.
C# program that times char array
using System;
using System.Diagnostics;
using System.Text;
class Program
{
const int _max = 1000000;
static void Main()
{
var s1 = Stopwatch.StartNew();
// Version 1: use a new char array.
for (int i = 0; i < _max; i++)
{
char[] buffer = new char[100];
for (int v = 0; v < 100; v++)
{
buffer[v] = 'a';
}
string result = new string(buffer);
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use a StringBuilder.
for (int i = 0; i < _max; i++)
{
StringBuilder builder = new StringBuilder(100);
for (int v = 0; v < 100; v++)
{
builder.Append('a');
}
string result = builder.ToString();
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
}
}
Output
113.09 ns char array
298.61 ns StringBuilder
StringBuilder: This is easy to use and a great optimization, but it is far slower in simple cases. It can help in real programs.
Note: We used char arrays as an improvement in the alphanumeric sorting algorithm. This improved performance.
Alphanumeric SortResult: Char arrays can be around 7 times faster on certain tasks. Char buffers have a big performance advantage.
And: It is more exact if you can enforce the constraints of char arrays (like the fixed length).
Array LengthNote: 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