本文介绍了StringBuilder的或+ =的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到每秒约5的消息。他们每个人都有一个字符串,我串连到主字符串,其中包含所有被接收消息

I receive around 5 messages per second. Each of them has a string, which I concatenate to a master string that contains all the received messages

    string _masterText = "";
    public void AddNewMessage(string text)  // this is going to be call at least 5 times/second
    {
        _masterText += text;
    }

这是对appropiated办法做到这一点?或者我应该改用StringBuilder的,如:

Is this the appropiated way to do it? or should I use instead StringBuilder, like:

    StringBuilder _masterText = new StringBuilder();
    public void AddNewMessage(string text) // this is going to be call at least 5 times/second
    {
         _masterText.Append(text);
    }

感谢

推荐答案

的StringBuilder通常被认为是更好的选择,但在这种情况下,我会使用没有。

StringBuilder is generally considered the better option, but in this case I'd use neither.

即使StringBuilder的,以该速率的基础字符缓冲器很快本身足够大,以获得粘在大对象堆。这将导致对于需要保持运行一段时间的应用的健康问题。

Even with StringBuilder, at that rate the underlying character buffer will soon itself be large enough to get stuck on the Large Object Heap. This will cause problems for the health of an application that needs to stay running for a while.

相反,我会使用一个 System.Collections.Generic.List<字符串> 并调用它的。新增()方法,为每一个新的消息。根据你做的这些消息,你也可以找到其他集合类型更适合(也许问答LT;字符串> ),但这是方向,你应该去。通过使用集合,所使用的每个单独的串的存储器将不计入的收集对象的大小。相反,每个串将只用于引用添加几个字节。这将需要更长的时间来与压缩大对象堆遇到问题。

Instead, I'd use a System.Collections.Generic.List<string> and just call it's .Add() method for each new message. Depending on what you do with these messages you may also find another collection type is more appropriate (perhaps a Queue<string>), but this is the direction you should go. By using a collection, the memory used by each individual string will not count towards the size of the collection object. Instead, each string will only add a few bytes for the reference. This will take a lot longer to run into problems with compacting the Large Object Heap.

如果您仍然有切换到采集后的问题,你可以使用的的,并写入字符串到磁盘。这样一来,你永远不会有一个以上的字符串中的RAM的时间。现在,你有问题的唯一方法是,如果个别字符串是85000字节或更大。

If you still have problems after switching to a collection, you can use a stream, and write the strings to disk. This way, you never have more than one string in RAM at a time. Now, the only way you have problems is if individual strings are 85000 bytes or larger.

这篇关于StringBuilder的或+ =的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:05