C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
New: In this example, please notice how the char[] variable is allocated before CopyTo is invoked.
Char ArrayVoid: CopyTo() is void, and returns nothing. The char array in the program instead has its characters changed internally in CopyTo.
Note: Arrays are indexed by their offsets. The fourth character where the CopyTo method begins copying is the letter "N".
Then: That character and the two following characters are copied into the char[] buffer and the buffer's values are printed to the screen.
ConsoleC# program that uses CopyTo
using System;
class Program
{
static void Main()
{
// Declare a string constant and an output array.
string value1 = "The Dev Codes";
char[] array1 = new char[3];
// Copy the fifth, sixth, and seventh characters to the array.
value1.CopyTo(4, array1, 0, 3);
// Output the array we copied to.
Console.WriteLine("--- Destination array ---");
Console.WriteLine(array1.Length);
Console.WriteLine(array1);
}
}
Output
--- Destination array ---
3
Net
Important: For longer strings, the benchmark would need to be adjusted. Careful testing is needed.
Version 1: Copy chars from a string into a char array with CopyTo. Only 4 chars are copied.
Version 2: Copy those same 4 chars into the char array with a for-loop. Use an index expression to assign elements.
Result: I found that the for-loop is faster. This of course depends on your system and other factors.
C# program that benchmarks CopyTo, for-loop
using System;
using System.Diagnostics;
class Program
{
const int _max = 100000000;
static void Main()
{
char[] values = new char[100];
// Version 1: use CopyTo.
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
"1234".CopyTo(0, values, 0, 4);
}
s1.Stop();
// Version 2: use for-loop.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
for (int j = 0; j < "1234".Length; j++) // [For-loop]
{
values[j] = "1234"[j];
}
}
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"));
Console.Read();
}
}
Output
11.44 ns, CopyTo
8.64 ns, For-loop
However: Using CopyTo is reliable because it has been extensively tested. The unsafe code is not your responsibility.
Wstrcpy: The CopyTo method internally calls into wstrcpy, which is a heavily optimized and unrolled loop. It copies characters quickly.
But: CopyTo() along with ToCharArray can be used as optimizations. And CopyTo can help when char arrays are needed by other methods.
ToCharArray