今天,碰到了在C#中对字符串的拼接。在计算机中,拼接是字符串拷贝的合理运用,显然,应该研究字符串拷贝的速度的快慢。
笔者在以前,研究过Golang语言的不同字符串的拼接,详见笔者的博客《golang字符串拼接方式》(https://blog.csdn.net/wangzhezhilu001/article/details/91421451)。
笔者今天又碰到了字符串拼接形式。
笔者发现,C#中字符串拼接(拷贝)有三种方式:
1)Array.Copy;
2)Buffer.BlockCopy;
3)CopyTo;
相关资料给的结果是:Buffer.BlockCopy是最快的, Array.Copy其次。
笔者试验了下,程序如下:
using System;
class Example
{
static int RunCount = 1000000;
public static void Main()
{
byte[] byteSource = new byte[1] { 11 };
byte[] byteDes = new byte[1] { 11 };
DateTime dt1 = DateTime.Now;
for (int i = 0; i < RunCount; i++)
{
Array.Copy(byteSource, byteDes, byteSource.Length);
}
DateTime dt2 = DateTime.Now;
Console.WriteLine("Array.Copy " + (dt2 - dt1).Milliseconds + " 毫秒");
DateTime dt3 = DateTime.Now;
for (int i = 0; i < RunCount; i++)
{
Buffer.BlockCopy(byteSource, 0, byteDes, 0, byteSource.Length);
}
DateTime dt4 = DateTime.Now;
Console.WriteLine("Buffer.BlockCopy " + (dt4 - dt3).Milliseconds + " 毫秒");
DateTime dt5 = DateTime.Now;
for (int i = 0; i < RunCount; i++)
{
byteSource.CopyTo(byteDes, 0);
}
DateTime dt6 = DateTime.Now;
Console.WriteLine("byteSource.CopyTo " + (dt6 - dt5).Milliseconds + " 毫秒");
Console.Read();
}
}
运行结果如下:
验证了结论。
但资料又给了说明:Array.Copy存在有重要意义。
因为,计算机分为大根端和小根端,Buffer.BlockCopy()访问数组元素索引下的字节取决于执行应用程序的计算机字节序,直接用可能会造成错误。
验证程序如下:
using System;
class Example
{
// Display the individual bytes in the array in hexadecimal.
public static void DisplayArray(Array arr, string name)
{
Console.WindowWidth = 120;
Console.Write("{0,11}:", name);
for (int ctr = 0; ctr < arr.Length; ctr++)
{
byte[] bytes;
if (arr is long[])
bytes = BitConverter.GetBytes((long)arr.GetValue(ctr));
else
bytes = BitConverter.GetBytes((short)arr.GetValue(ctr));
foreach (byte byteValue in bytes)
Console.Write(" {0:X2}", byteValue);
}
Console.WriteLine();
}
// Display the individual array element values in hexadecimal.
public static void DisplayArrayValues(Array arr, string name)
{
// Get the length of one element in the array.
int elementLength = Buffer.ByteLength(arr) / arr.Length;
string formatString = String.Format(" {{0:X{0}}}", 2 * elementLength);
Console.Write("{0,11}:", name);
for (int ctr = 0; ctr < arr.Length; ctr++)
Console.Write(formatString, arr.GetValue(ctr));
Console.WriteLine();
}
public static void Main()
{
short[] srcTest = { 258, 259, 260, 261, 262, 263, 264,
265, 266, 267, 268, 269, 270 };
long[] destTest = new long[srcTest.Length + 1];
Array.Copy(srcTest, destTest, srcTest.Length);
DisplayArrayValues(srcTest, "srcTest");
DisplayArrayValues(destTest, "destTest");
Buffer.BlockCopy(srcTest, 0, destTest, 0, srcTest.Length);
DisplayArrayValues(srcTest, "srcTest");
DisplayArrayValues(destTest, "destTest");
Console.Read();
}
}
向long型数组拷贝short数据,运行结果如下:
可知:当使用Buffer.BlockCopy会在成根堆错误,从而可能造成数据错误。