Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimize loop in ASP.Net / C#

I wrote a loop to display each line one by one from a List of string. The problem is that the list contains more that 45,000 lines and its taking a lot of time to create the page for displaying.

Can someone please help in optimizing the code !

        List<string> OverrrideLog = lc.getOverrideLog();
        List<string> AccessLog = lc.getAccessLog();

        foreach (string s in OverrrideLog)
            lblOverrideLog.Text += s + "<br/>";

        foreach (string s in AccessLog)
            lblAccessLog.Text += s + "<br/>";

Here lblOverrideLog and lblAccessLog are literals and each list has more than 22,000 lines.

like image 297
Maverick Avatar asked Jan 18 '23 20:01

Maverick


2 Answers

You can use the String.Join Method (String, IEnumerable):

List<string> OverrrideLog = lc.getOverrideLog();
List<string> AccessLog = lc.getAccessLog();

lblOverrideLog.Text = String.Join("<br />", OverrrideLog);
lblAccessLog.Text = String.Join("<br />", AccessLog);

(See also String.Join vs. StringBuilder: which is faster?)

like image 155
CD.. Avatar answered Jan 29 '23 11:01

CD..


Untested but try this:

List<string> OverrrideLog = lc.getOverrideLog();
List<string> AccessLog = lc.getAccessLog();

StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();

foreach(var el in OverrrideLog)
{
  sb.Append(el);
  sb.Append(" <br />");
}

foreach(var el in AccessLog)
{
  sb2.Append(el);
  sb2.Append(" <br />");
}

lblOverrideLog.Text = sb.ToString();
lblAccessLog.Text = sb2.ToString();

Edit:

woops, put val instead of var

like image 33
Stuart Blackler Avatar answered Jan 29 '23 10:01

Stuart Blackler