Here we measure the performance of ToCharArray. We copy a string to a char array with 2 versions of C# code.
using System;
using System.Diagnostics;
const int _max = 2000000;
// Create 500-char string.
string text = new string('P', 500);
// Version 1: use ToCharArray.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
char[] result = text.ToCharArray();
if (result[0] != 'P')
{
return;
}
}
s1.Stop();
// Version 2: copy chars from string with loop.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
char[] result = new char[text.Length];
for (int v = 0; v < text.Length; v++)
{
result[v] = text[v];
}
if (result[0] != 'P')
{
return;
}
}
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"));
68.30 ns ToCharArray
323.36 ns new char[], for loop