【问题标题】:Stream to UTF8 String, without the byte[]流式传输到 UTF8 字符串,没有字节 []
【发布时间】:2015-12-27 06:31:34
【问题描述】:

我有一个流,其下一个 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 或技术吗?

【问题讨论】:

  • 你可以继承 Stream 来创建一个 TruncatedProxyStream 来包装原始流并从底层流中读取最多 n 字节。然后将其传递给StreamReader
  • 这些byte[] 临时对象有多大?问题是您分配了大量的小数组,还是分配了一些最终在large object heap 上的大数组?
  • @dbc,它会将它们读入什么内容?理想情况下,我是一个直接写入字符串支持数据 char[]. 的实现
  • @dbc 我正在尝试最大化吞吐量。许多字符串相对较短,但没有上限。

标签: c# .net performance character-encoding stream


【解决方案1】:

如果您使用可变长度的 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);

【讨论】:

  • 只是为了关闭循环,Stream 上没有不安全的Stream.Read(byte *buffer, int offset, int count) 方法允许从流中读取 n 个字节到不安全的数组中。如果有,那么复制CreateStringFromEncoding() 的逻辑可能会很高效。
  • 以这种方式调用ReadByte的另一个问题是没有检测到EOS(-1)。似乎这里的限制是,如果不使用数组,就无法从流中获取多个字节。我确实尝试过重用线程本地数组,但发现它会损害性能。虽然不完全确定为什么,所以我会尝试更多。
【解决方案2】:

对于那些不想实现自己的数组重用逻辑并且不想处理不安全代码的人来说,ArrayPool&lt;T&gt; class 可用于 .NET Core、.NET 5+、.NET Standard 2.1 + 和Span&lt;T&gt; struct

使用ArrayPool&lt;T&gt;

顾名思义,它允许您重用数组,从而减少 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&lt;T&gt;

如果您确定您的流长度 n 永远不会变得太大,您甚至可以使用 stackallocSpan&lt;T&gt; 使您的代码更快,因为根本不涉及 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# 中的 Stack 容量见this question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2019-03-20
    • 2012-10-14
    相关资源
    最近更新 更多