views:

105

answers:

3

I have a custom logging framework writing to a System.Windows.Forms.TextBox. The way i am writing to the TextBox now is like this:

tbLog.Text += newLogEntry.Text;

The problem with this approach is that each time this is executed the strings from the tbLog.Text and newLogEntry.Text are concatenated, and then assigned to tbLog.Text. As the log in the TextBox grows the operation becomes very memory intensive and increasingly slower.

Is there any way of doing this quicker and more efficient?

+1  A: 

The 'problem', is that appending a string to another string, results each time in a new string. This can be quite expensive when you do a lot of concats.

If I were you, I wouldn't log directly to the TextBox. I would just keep track of al the log messages, and use a Textbox to visualize the log. By doing so, you can for instance choose to save the log to a text-file as well, or choose to visualize the log in any other way.

You could for instance, keep the messages in a StringCollection or List<String>. Instead of visualizing it in a textbox, you could use a ListBox for instance, and every time you add a new item to the log, you could add a new item to the ListBox. But, I would make sure that this isn't tightly coupled. Your log class could fire an event for instance every time a new message is saved to the log. You could then have different 'observers', that keep track of the log, by subscribing to the events, and take appropriate action each time the event is raised.

Frederik Gheysels
+1  A: 

Personally, I would do all the work within a StringBuilder using .Append() first. I would then set the textbox text property using the .ToString() method on the StringBuilder.

garpunkal
Isn't this what happens now?
m0sa
No, you aren't using a stringbuilder.
Frederik Gheysels
Ok. I misunderstood your answer.. I think you meant I should do something like this:var sb = new StringBuilder(tbLog.Text);sb.AppendLine(newLogEntry.Text);tbLog.Text= sb.ToString()But now I'm using a string builder as a class variable in the logger class and just append to it each time a new entry files by..
m0sa
+2  A: 

The TextBox has a function AppendText(). You should use this instead, cause it peforms much better than the += operator.

Oliver