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

德鲁·诺克斯(Drew Noakes)

我有一个流,其后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类没有与流工作方法。

如果可以,我可以使用不安全的代码。我不能重用一个byte[]缓冲区,否则缓冲区所带来的ThreadLocal<byte[]>开销似乎超出其缓解的范围。我确实需要支持UTF8(ASCII不会削减它)。

我这里缺少API或技术吗?

Yoh Deadfall

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

让我们看看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在其上使用但是您会因为Stream.ReadByte多次调用而失去性能,因为没有Stream.Read哪个byte*参数可以接受

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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

将字节缓冲区转换为UTF8字符串

来自分类Dev

UTF8字符串为int

来自分类Dev

python用3个字节的utf8字符拆分unicode字符串

来自分类Dev

如何将UTF8字符串转换为字节数组?

来自分类Dev

utf16字符串作为utf8字符串的长度

来自分类Dev

Python:将utf-8字符串转换为字节字符串

来自分类Dev

Python:将utf-8字符串转换为字节字符串

来自分类Dev

如何删除python字符串的最后utf8字符

来自分类Dev

如何知道Javascript字符串中是否有UTF8字符?

来自分类Dev

Swift 2 Json utf8字符串字符错误

来自分类Dev

为什么在Julia中不建议对UTF8字符串进行索引?

来自分类Dev

Perl中的JSON编码/解码utf8字符串

来自分类Dev

Python将UTF8字符串插入SQLite

来自分类Dev

计算UTF8字符串的MD5哈希

来自分类Dev

如何在python中构建utf8字符串

来自分类Dev

在Microsoft本地数据库中读写utf8字符串

来自分类Dev

Django with MySQL:无效的utf8字符串:“ 800363”如何解决?

来自分类Dev

使用brotli压缩和解压缩utf8字符串

来自分类Dev

使用utf8字符串创建存储过程

来自分类Dev

从服务器响应解析utf8字符串

来自分类Dev

如何在OS X终端中显示UTF8字符串

来自分类Dev

Perl中的JSON编码/解码utf8字符串

来自分类Dev

正确处理从json.net接收到的utf8字符串

来自分类Dev

从MPMoviePlayerController元数据中的UTF8字符串中快速读取

来自分类Dev

QT应用翻译中的UTF8字符串显示错误

来自分类Dev

向后遍历utf8多字节字符串

来自分类Dev

向后遍历utf8多字节字符串

来自分类Dev

在utf8中编码字节字符串

来自分类Dev

UTF8字符串上的==是否安全?