I have tried to look up a reason as to why this loop is so slow, but I havent gotten a good answer yet. The following loop takes over a minute to execute:
string answer = "";
string headers = "";
string datarows = "";
bool firstRun = true;
foreach (Dictionary<string, string> row in JSON)
{
datarows += "<tr>";
foreach (KeyValuePair<String, String> cell in row)
{
if (firstRun) { headers += "<th>" + cell.Key + "</th>"; }
datarows += "<td>" + cell.Value + "</td>";
}
datarows += "</tr>";
firstRun = false;
}
answer += "<table><tr>" + headers + "</tr>" + datarows + "</table>";
return answer;
The JSON variable is a List and contains about 1150 dictionaries. Each dictionary contains 9 key value pairs. Any thoughts?
The obvious issue that springs out is your string concatenation.
Every time you append to a string, you are actually appending to a copy of the string (as the strings individually are immutable). This can be extremely costly.
You should prefer either a StringBuilder, or, for generating HTML like this, you might want to investigate the HtmlTextWriter – this will help take care of the “well-formed-ness” of the HTML amongst other things.