流到UTF8字符串,不带字节[]

本文关键字:字节 UTF8 字符串 流到 | 更新日期: 2023-09-27 18:28:19

我有一个流,它的下一个N字节是UTF8编码的字符串。我想用最少的开销创建那个字符串。

这项工作:

var bytes = new byte[n];
stream.Read(bytes, 0, n); // my actual code checks return value
var str = Encoding.UTF8.GetString(bytes);

在我的基准测试中,我看到相当多的时间花在收集byte[]临时性形式的垃圾上。如果我能去掉这些,我就可以有效地将堆分配减半。

UTF8Encoding类没有用于处理流的方法。

如果有帮助的话,我可以使用不安全的代码。如果没有ThreadLocal<byte[]>,我就无法重用byte[]缓冲区,这似乎会带来更多的开销。我确实需要支持UTF8(ASCII不会削减它)。

这里是否缺少API或技术?

流到UTF8字符串,不带字节[]

如果使用可变长度的UTF8编码,则无法避免分配byte[]。因此,只有在读取了所有这些字节之后,才能确定结果字符串的长度。

让我们看看UTF8Encoding.GetString方法:

public override unsafe String GetString(byte[] bytes, int index, int count)
{
    // Avoid problems with empty input buffer
    if (bytes.Length == 0) return String.Empty;
    fixed (byte* pBytes = bytes)
        return String.CreateStringFromEncoding(
            pBytes + index, count, this);
}

它调用String.CreateStringFromEncoding方法,该方法首先获取得到的字符串长度,然后对其进行分配,并在没有额外分配的情况下用字符填充。UTF8Encoding.GetChars也不分配任何内容。

unsafe static internal String CreateStringFromEncoding(
    byte* bytes, int byteLength, Encoding encoding)
{
    int stringLength = encoding.GetCharCount(bytes, byteLength, null);
    if (stringLength == 0)
        return String.Empty;
    String s = FastAllocateString(stringLength);
    fixed (char* pTempChars = &s.m_firstChar)
    {
        encoding.GetChars(bytes, byteLength, pTempChars, stringLength, null);
    }
}

如果使用固定长度编码,则可以直接分配字符串并对其使用Encoding.GetChars。但是,由于没有接受byte*作为参数的Stream.Read,因此多次调用Stream.ReadByte会失去性能。

const int bufferSize = 256;
string str = new string(''0', n / bytesPerCharacter);
byte* bytes = stackalloc byte[bufferSize];
fixed (char* pinnedChars = str)
{
    char* chars = pinnedChars;
    for (int i = n; i >= 0; i -= bufferSize)
    {
        int byteCount = Math.Min(bufferSize, i);
        int charCount = byteCount / bytesPerCharacter;
        for (int j = 0; j < byteCount; ++j)
            bytes[j] = (byte)stream.ReadByte();
        encoding.GetChars(bytes, byteCount, chars, charCount);
        chars += charCount;
    }
}

因此,您已经使用了更好的方法来获取字符串。在这种情况下,唯一可以做的就是实现ByteArrayCache类。它应该类似于StringBuilderCache

public static class ByteArrayCache
{
    [ThreadStatic]
    private static byte[] cachedInstance;
    private const int maxArraySize = 1024;
    public static byte[] Acquire(int size)
    {
        if (size <= maxArraySize)
        {
            byte[] instance = cachedInstance;
            if (cachedInstance != null && cachedInstance.Length >= size)
            {
                cachedInstance = null;
                return instance;
            }
        }
        return new byte[size];
    }
    public static void Release(byte[] array)
    {
        if ((array != null && array.Length <= maxArraySize) &&
            (cachedInstance == null || cachedInstance.Length < array.Length))
        {
            cachedInstance = array;
        }
    }
}

用法:

var bytes = ByteArrayCache.Acquire(n);
stream.Read(bytes, 0, n);
var str = Encoding.UTF8.GetString(bytes);
ByteArrayCache.Release(bytes);

对于那些不想实现自己的数组重用逻辑并且不想处理不安全代码的人,ArrayPool<T>类可用于.NET Core、.NET 5+、.NET Standard 2.1+和Span<T>结构。

使用ArrayPool<T>

顾名思义,它允许您重用数组,从而减少GC开销。

你的代码看起来像这样:

// rent an existing byte array instead of creating a new one
var bytes = ArrayPool<byte>.Shared.Rent(n); 
// do your thing ...
stream.Read(bytes, 0, n);
var str = Encoding.UTF8.GetString(bytes);
// return the rented array so it can be reused. 
//Optionally you can tell the array pool class to clear it too if you want an empty array in the next reuse-cycle.
ArrayPool<byte>.Shared.Return(buffer);

使用Span<T>

如果你确信你的流长度n永远不会太大,你甚至可以使用stackallocSpan<T>使你的代码更快,因为GC根本不涉及(堆栈内存很便宜)。

// Create your buffer.
Span<byte> bytes = stackalloc byte[n];
// do your thing ...
stream.Read(bytes);
var str = Encoding.UTF8.GetString(bytes);
// don't need to free or GC collect anything. Your buffer will just be popped off the stack once the method returns.

再次注意不要让n的巨大值溢出堆栈。请参阅这个关于c#中堆栈容量的问题。