At a guess, you're serializing each row to a
string
and concatenating it to a larger string - eg:
string result = "";
foreach (var row in table)
{
result += SerializeToJson(row);
}
String concatenation in a loop is horrendously slow. For each row, you have to create a new
string
, copy the characters from the existing string, append the characters from the new string, and store the result in the variable.
Instead, you should use a
StringBuilder[
^], or stream the results to the output directly.
var sb = new StringBuilder();
foreach (var row in table)
{
sb.Append(SerializeToJson(row));
}
string result = sb.ToString();
using (Stream stream = File.Create("... some path ..."))
using (TextWriter writer = new StreamWriter(stream))
{
foreach (var row in table)
{
writer.Write(SerializeToJson(row));
}
}
using (Stream stream = File.Create("... some path ..."))
using (TextWriter writer = new StreamWriter(stream))
using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
{
JsonSerializer serializer = new JsonSerializer();
foreach (var row in table)
{
serializer.Serialize(jsonWriter, row);
}
}
How to concatenate multiple strings (C# Guide) | Microsoft Docs[
^]