public static int GetBytesByByte(string text)
{
byte[] buffer = new byte[256];
return Encoding.UTF8.GetBytes(text, 0, text.Length, buffer, 0);
}
public static int GetBytesByStackalloc(string text)
{
Span buffer = stackalloc byte[256];
return Encoding.UTF8.GetBytes(text, buffer);
}
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
string text = Guid.NewGuid().ToString() + Guid.NewGuid().ToString();
int iterations = 10_000_000; // 執行次數
// --- 用 new byte[] ---
var sw1 = Stopwatch.StartNew();
for (int round = 1; round <= 10; round++)
{
Parallel.For(0, iterations, i =>
{
GetBytesByByte(text);
});
}
Console.WriteLine($"new byte[] 花費時間:{sw1.ElapsedMilliseconds} ms");
sw1.Stop();
// --- 用 stackalloc ---
var sw2 = Stopwatch.StartNew();
for (int round = 1; round <= 10; round++)
{
Parallel.For(0, iterations, i =>
{
GetBytesByStackalloc(text);
});
}
Console.WriteLine($"stackalloc 花費時間:{sw2.ElapsedMilliseconds} ms");
sw2.Stop();
}
結果:
new byte[] 花費時間:3675 ms
stackalloc 花費時間:955 ms
new byte[] 花費時間:3599 ms
stackalloc 花費時間:951 ms
new byte[] 花費時間:3951 ms
stackalloc 花費時間:875 ms
new byte[] 花費時間:3662 ms
stackalloc 花費時間:905 ms