此功能不是生产质量,如何使其更强大?

时间:2019-01-09 14:36:03

标签: c# arrays string memory .net-core

.NET CORE 2.1,C#7.2是此代码所必需。

private const int BUFFER_LENGTH = 512;

        var buffer = new Memory<byte>(new byte[BUFFER_LENGTH]); // Allocate 512 byte buffer

        var count = await ReadFromUrlAsync("https://www.microsoft.com", buffer).ConfigureAwait(false); // Gets first 512 bytes of HTML body from web, just random text to fill the buffer
        Console.WriteLine("Bytes: {0}" + Environment.NewLine, count);

        StringBuilder sb = new StringBuilder(capacity: BUFFER_LENGTH);
        foreach (var val in buffer.ToArray()) // I think I just allocated memory here, can I do this with something more like pointer arithmetic?
        {
            sb.Append((char)val); // I feel like this operation would cause a lot of copying and allocation, am I wrong?
        }
        Console.WriteLine(sb); // Perhaps there's a way to do this without StringBuilder?

请注意上面代码中的注释。

从我要在此处完成的工作的角度来看,使用新的T类型的Span的主要目的是在可能的情况下避免额外的内存分配。除了强制将每个元素复制到StringBuilder中之外,是否还有一种更健壮和/或低级的方法可以将字节Span转换为char [] / string?

1 个答案:

答案 0 :(得分:1)

您可以将UTF8Encoding.GetString()替换为StringBuilder和foreach