简体   繁体   English

我如何优化此C#代码?

[英]How can i optimize this c# code?

I have converted my Datatable to json string use the following method... 我已经使用以下方法将Datatable转换为json字符串...

public string GetJSONString(DataTable Dt)
{
    string[] StrDc = new string[Dt.Columns.Count];
    string HeadStr = string.Empty;
    for (int i = 0; i < Dt.Columns.Count; i++)
    {
        StrDc[i] = Dt.Columns[i].Caption;
        HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
    }
    HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
    StringBuilder Sb = new StringBuilder();

    Sb.Append("{\"" + Dt.TableName + "\" : [");
    for (int i = 0; i < Dt.Rows.Count; i++)
    {
        string TempStr = HeadStr;
        Sb.Append("{");
        for (int j = 0; j < Dt.Columns.Count; j++)
        {
            if (Dt.Rows[i][j].ToString().Contains("'") == true)
            {
                Dt.Rows[i][j] = Dt.Rows[i][j].ToString().Replace("'", "");
            }
            TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString());
        }
        Sb.Append(TempStr + "},");
    }
    Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
    Sb.Append("]}");
    return Sb.ToString();
}

Is this fair enough or still there is margin for optimization to make it execute faster.... Any suggestion... 这足够公平还是仍然有优化的余地,以使其执行更快。...任何建议...

There may well be ways of getting it to execute faster - but do you have any indication that you need it to execute faster? 也许有很多方法可以使其更快地执行-但是您是否有迹象表明需要它更快地执行? Do you have a good reason to believe this is a significant bottleneck in your code? 您是否有充分的理由相信这是代码中的重要瓶颈? If so, benchmark the code with some real data and profile the routine to work out where the time is going. 如果是这样,请使用一些实际数据对代码进行基准测试,并分析例程以弄清楚时间的流逝。

Before asking if you can optimise it to make it execute faster, the first question you need to ask yourself is, does it run fast enough for me? 在询问是否可以对其进行优化以使其更快地执行之前,您需要问自己的第一个问题是,它对我来说足够快地运行吗? Premature optimisation is the curse of all of us (I know I've done it!). 过早的优化是我们所有人的诅咒(我知道我已经做到了!)。 You could spend hours trying to micro-optimise this code, which might take it from taking, for example, 20ms to execute down to 15ms. 您可能需要花费数小时来尝试对该代码进行微优化,例如,可能需要20毫秒才能执行到15毫秒。 Yes that'd be a reduction of 25%, but would 5ms really be worth 2 hours of your time? 是的,这将减少25%,但是5毫秒真的值2小时的时间吗? More importantly, would it provide enough of a benefit to your end users to warrant it? 更重要的是,它将为您的最终用户提供足够的利益以保证它吗?

Have you considered using the JsonSerializer from "Newtonsoft" ? 您是否考虑过使用“ Newtonsoft”中JsonSerializer This may well be "quick enough", is fairly widely used and is thus more likely to be correct overall than anything I, or you, can write first time round. 这可能“足够快”,已被广泛使用,因此比我或您第一次可以写的任何东西总体上更正确。

Purely from a readability perspective (that may also allow the C# compiler / CLR to improve thing for you) you could consider changing long bits of string concatenation such as: 纯粹从可读性的角度(这也可能允许C#编译器/ CLR为您改进),您可以考虑更改长字符串串联,例如:

HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";

To: 至:

HeadStr += string.Format("\"{0}\" : \"{0}{1}¾\",", strDc[i], i);

But for any changes you do make. 但是对于您所做的任何更改。 Measure, Rinse, Repeat =) 测量,冲洗,重复=)

You could tidy up some bits: 您可以整理一下:

  1. Use string.Format() to avoid long x + y + z sequences. 使用string.Format()避免长的x + y + z序列。 This may or may not make things faster (it would be marginal either way). 这可能会或可能不会使事情变得更快(无论哪种方式都很少)。
  2. You usually don't need .toString() when concatenating. 串联时通常不需要.toString()

You could also pass in the StringBuffer to be populated, so that the caller might have the opportunity to bundle up several such operations into a single StringBuffer . 您还可以传入要填充的StringBuffer ,以便调用者可以将多个此类操作捆绑为一个StringBuffer

These suggestions are focused more on tidiness than performance, which I think should be the real focus unless this code is presenting as a bottleneck in your profiling. 这些建议更多地关注整理而不是性能,我认为这应该是真正的关注点,除非此代码在性能分析中成为瓶颈。

Why do you think it needs optimization? 您为什么认为它需要优化? Is it really slow on some DataTables? 在某些数据表上真的很慢吗? I'd just serialize DataTable with something like newton JSON serializer, if it's serializable at all. 如果只是可序列化的话,我将使用诸如Newton JSON序列化器之类的数据表进行序列化。

Refactor your code, use a tool like ReSharper, JustCode etc to tidy it up a bit. 重构代码,使用ReSharper,JustCode等工具整理一下代码。 Extract methods and use individual tests ( Test Driven Development-ish ) to find bottlenecks in your code and then tweak those. 提取方法并使用单个测试(Test Driven Development-ish)在代码中找到瓶颈,然后进行调整。

But your first step should be: Refactor! 但是您的第一步应该是: 重构!

The problem with the code isn't speed, but that it's not cleaned up. 代码的问题不是速度,而是没有清理。 I've done some clean-up, but you could probably do even more: 我已经做了一些清理工作,但是您可能可以做更多的事情:

public string GetJSONString2(DataTable table)
{
    StringBuilder headStrBuilder = new StringBuilder(table.Columns.Count * 5); //pre-allocate some space, default is 16 bytes
    for (int i = 0; i < table.Columns.Count; i++)
    {
        headStrBuilder.AppendFormat("\"{0}\" : \"{0}{1}¾\",", table.Columns[i].Caption, i);
    }
    headStrBuilder.Remove(headStrBuilder.Length - 1, 1); // trim away last ,

    StringBuilder sb = new StringBuilder(table.Rows.Count * 5); //pre-allocate some space
    sb.Append("{\"");
    sb.Append(table.TableName);
    sb.Append("\" : [");
    for (int i = 0; i < table.Rows.Count; i++)
    {
        string tempStr = headStrBuilder.ToString();
        sb.Append("{");
        for (int j = 0; j < table.Columns.Count; j++)
        {
            table.Rows[i][j] = table.Rows[i][j].ToString().Replace("'", "");
            tempStr = tempStr.Replace(table.Columns[j] + j.ToString() + "¾", table.Rows[i][j].ToString());
        }
        sb.Append(tempStr + "},");
    }
    sb.Remove(sb.Length - 1, 1); // trim last ,
    sb.Append("]}");
    return sb.ToString();
}

I would suggest a different solution,if you are using .net 3.0 or 3.5 如果您使用的是.net 3.0或3.5,我建议使用其他解决方案

instead of doing this 而不是这样做

  1. Convert datatable into xml 将数据表转换为xml
  2. use xmlserializer to convert the xml to your domain object 使用xmlserializer将xml转换为您的域对象
  3. Using JavaScriptSerializer(System.Web.Extensions.dll) to serialize the domain object to json string. 使用JavaScriptSerializer(System.Web.Extensions.dll)将域对象序列化为json字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM