0

I'm working a GUI project in C#, and i have this multi-lined textbox. Whenever something happens within the application, it outputs a line to the textbox, logging a small desc of what happened. I want to only display the last 100 or so entries to prevent memory or performance issues. What is the best way to do this? My current code is as so:

        string[] CurrentLines = LogWindow.Lines;
        Array.Reverse(CurrentLines);
        Array.Resize<string>(ref CurrentLines, 100);
        Array.Reverse(CurrentLines);
        LogWindow.Lines = CurrentLines;

This whole method just seems really redundant and slow to me. Can anyone give me a better way please?

Wilson212
  • 543
  • 6
  • 17

1 Answers1

0

Using the SubArray code snippet from this SO post:

public static T[] SubArray<T>(this T[] data, int index, int length)
{
    T[] result = new T[length];
    Array.Copy(data, index, result, 0, length);
    return result;
}

You can get your 100 last LogLines from your lines array (avoiding costly Reverse)

However it doesn't seem optimal at all.

A better implementation would be to use a Queue of fixed size 100 as the structure for your text box: when a new log lines arrives, pop a line from the queue (the oldest), and push the new line, then refresh your textbox by rewriting the stack content into it.

This way you would avoid both the reverse operations and the dynamic allocations.

Community
  • 1
  • 1
quantdev
  • 23,517
  • 5
  • 55
  • 88