首页 > 解决方案 > 我该如何优化

问题描述

这是我的代码,需要很长时间才能将信息插入 json

ListarRegistrosFormularioContacto: {0}", stopwatch.Elapsed);
objLog.InsertarLog($"SolicitarReporteFormularios: { idPeticion }", $"Tiempo de carga ListarRegistrosFormularioContacto: { stopwatch.Elapsed }, por tamaño de { dtRegistros.Rows.Count }");

if (dtRegistros.Rows.Count > 0)
{
    string dataSerialize = "[";

    stopwatch.Reset();
    stopwatch.Restart();

    for (int x = 0; x < dtRegistros.Rows.Count; x++)
    {
        if (x > 0) { dataSerialize += ", "; }

        dynamic registro = new ExpandoObject();

        for (int col = 0; col < dtRegistros.Columns.Count; col++)
        {
            AddPropertyToExpadoObject(registro, dtRegistros.Columns[col].ColumnName, dtRegistros.Rows[x][col].ToString());
        }

        dataSerialize += JsonConvert.SerializeObject(registro);
    }

    stopwatch.Stop();

    objLog.InsertarLog($"SolicitarReporteFormularios: { idPeticion }", $"Tiempo de termino de lectura de registros ( for ) : { stopwatch.Elapsed }");

    dataSerialize += "]";

    stopwatch.Reset();
    stopwatch.Restart();

    string filename = $"{DateTime.Now.ToString("ddMMyyyyHHmmss")}.json";
    string path = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/Files/reporte-formulario.json");
    File.WriteAllText(path: path, contents: dataSerialize);

    stopwatch.Stop();

    objLog.InsertarLog($"SolicitarReporteFormularios: { idPeticion }", $"Pinta los registros en el archivo json : { stopwatch.Elapsed }");

    stopwatch.Reset();
    stopwatch.Restart();

有什么想法吗?我的 SQL 很快,需要几秒钟,但转换为 json 需要 5 分钟或更长时间

所以另一个问题(因为时间)是我的应用服务正在发送超时(每个请愿书 230 秒)

数据来自 11k-25k 行,时间用于从 SQL 到 JSON 的结果转换。

问题已经用Stringbuilder解决了,我明天贴代码,谢谢!

现在是:

新代码

所以这个时间只有20秒,谢谢大家的帮助

标签: c#json

解决方案


正如评论所说,问题已通过 StringBuilder 解决。从 17 分钟到 20 秒


推荐阅读