Byron Whitlock
Byron Whitlock

Reputation: 53921

Writing huge amounts of text to a textbox

I am writing a log of lots and lots of formatted text to a textbox in a .net windows form app.

It is slow once the data gets over a few megs. Since I am appending the string has to be reallocated every time right? I only need to set the value to the text box once, but in my code I am doing line+=data tens of thousands of times.

Is there a faster way to do this? Maybe a different control? Is there a linked list string type I can use?

Upvotes: 10

Views: 7622

Answers (4)

James in Indy
James in Indy

Reputation: 2884

I have found that setting the textbox's WordWrap property to false greatly improves performance, as long as you're ok with having to scroll to the right to see all of your text. In my case, I wanted to paste a 20-50 MB file into a MultiLine textbox to do some processing on it. That took several minutes with WordWrap on, and just several seconds with WordWrap off.

Upvotes: 0

Kent Boogaart
Kent Boogaart

Reputation: 178760

No one has mentioned virtualization yet, which is really the only way to provide predictable performance for massive volumes of data. Even using a StringBuilder and converting it to a string every half a second will be very slow once the log gets large enough.

With data virtualization, you would only hold the necessary data in memory (i.e. what the user can see, and perhaps a little more on either side) whilst the rest would be stored on disk. Old data would "roll out" of memory as new data comes in to replace it.

In order to make the TextBox appear as though it has a lot of data in it, you would tell it that it does. As the user scrolls around, you would replace the data in the buffer with the relevant data from the underlying source (using random file access). So your UI would be monitoring a file, not listening for logging events.

Of course, this is all a lot more work than simply using a StringBuilder, but I thought it worth mentioning just in case.

Upvotes: 7

Paul Sasik
Paul Sasik

Reputation: 81517

StringBuilder will not help if the text box is added to incrementally, like log output for example.

But, if the above is true and if your updates are frequent enough it may behoove you to cache some number of updates and then append them in one step (rather than appending constantly). That would save you many string reallocations... and then StringBuilder would be helpful.

Notes:

  1. Create a class-scoped StringBuilder member (_sb)
  2. Start a timer (or use a counter)
  3. Append text updates to _sb
  4. When timer ticks or certain counter reached reset and append to text box
  5. restart process from #1

Upvotes: 7

Frank
Frank

Reputation: 2648

Build your String together with a StringBuilder, then convert it to a String using toString(), and assign this to the textbox.

Upvotes: 5

Related Questions