【问题标题】:This function is not production quality, how can I make it more robust? [closed]这个功能不是生产质量,我怎样才能使它更健壮? [关闭]
【发布时间】:2019-01-09 14:36:03
【问题描述】:

此代码需要 .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?

请注意上面代码中的 cmets。

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

【问题讨论】:

  • 我投票结束这个问题,因为它更适合Code Review Stack Exchange
  • @Alejandro 以后,请不要以 Code Review 网站的存在作为结束问题的理由。评估请求并使用太宽泛主要基于意见等原因。然后你可以向 OP 提及它可以发布在 Code Review 上,如果它是on-topicFlag it for Mod intervention。请参阅this answer to A guide to Code Review for Stack Overflow users 中的你不应该做的事情部分
  • 我在寻求一种优化代码的方法,这不是一个意见,这个函数中有三个内存分配,似乎可以优化为只使用两个分配,但是,我不知道该怎么做。比较资深和熟悉框架的人应该可以客观地回答这个问题。
  • 此外,这个问题的唯一答案就是所提问题的正确答案。

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


【解决方案1】:

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

【讨论】:

  • 优化代码:``` UTF8Encoding utf8 = new UTF8Encoding(true, true); if (convert) { Console.WriteLine(utf8.GetString(buffer.ToArray())); }```感谢您的完美回复!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-02
  • 2014-07-23
  • 2023-03-12
  • 2020-09-01
相关资源
最近更新 更多