在网络编程中,需要对数据进行序列化发送,那么如何能更快的序列化呢,string(字符串)部分
测试
C#
[MemoryDiagnoser]
public partial class Test
{
[GlobalSetup]
public void Startup()
{
}
string a = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
byte[] bytes = new byte[1024];
[Benchmark]
public void UTF8()
{
for (int i = 0; i < 100; i++)
Encoding.UTF8.GetBytes(a).CopyTo(bytes, 0);
}
[Benchmark]
public void UTF8New()
{
for (int i = 0; i < 100; i++)
a.AsSpan().ToUTF8Bytes(bytes);
}
[Benchmark]
public void UTF16()
{
for (int i = 0; i < 100; i++)
a.GetUTF16Bytes().CopyTo(bytes);
}
}
基准
C#
BenchmarkDotNet=v0.13.5, OS=Windows 10 (10.0.19045.3208/22H2/2022Update)
AMD Ryzen 3 2200G with Radeon Vega Graphics, 1 CPU, 4 logical and 4 physical cores
.NET SDK=7.0.100
[Host] : .NET 7.0.0 (7.0.22.51805), X64 RyuJIT AVX2 [AttachedDebugger]
DefaultJob : .NET 7.0.0 (7.0.22.51805), X64 RyuJIT AVX2
| Method | Mean | Error | StdDev | Gen0 | Allocated |
|-------- |-----------:|----------:|----------:|-------:|----------:|
| UTF8 | 5,256.1 ns | 102.87 ns | 133.77 ns | 4.2038 | 8800 B |
| UTF8New | 2,275.1 ns | 27.77 ns | 25.98 ns | - | - |
| UTF16 | 586.7 ns | 5.16 ns | 4.57 ns | - | - |
UTF8优化和UTF16
C#
public static int ToUTF8Bytes(this ReadOnlySpan<char> str, Memory<byte> bytes)
{
if (str.Length == 0) return 0;
Utf8.FromUtf16(str, bytes.Span, out var _, out var utf8Length, replaceInvalidSequences: false);
return utf8Length;
}
public static ReadOnlySpan<byte> GetUTF16Bytes(this string str)
{
if (str == null) return Helper.EmptyArray;
return MemoryMarshal.AsBytes(str.AsSpan());
}