【问题标题】:What should I use to optimize my c# code?我应该使用什么来优化我的 c# 代码?
【发布时间】:2022-01-03 10:05:40
【问题描述】:

我正在做一个 codewars kata,它正在工作,但我正在超时。 我在网上搜索了解决方案,以获取某种参考,但它们都是针对 java 脚本的。

这是卡塔:https://i.stack.imgur.com/yGLmw.png

这是我的代码:

public static int DblLinear(int n)
    {
        if(n > 0)
        {
            var list = new List<int>();
            int[] next_two = new int[2];
            list.Add(1);
            for (int i = 0; i < n; i++)
            {
                for (int m = 0; m < next_two.Length; m++)
                {
                    next_two[m] = ((m + 2) * list[i]) + 1;
                }
                if(list.Contains(next_two[0]))
                {
                    list.Add(next_two[1]);
                }
                else if(list.Contains(next_two[1]))
                {
                    list.Add(next_two[0]);
                }
                else
                list.AddRange(next_two);

                list.Sort();
            }
            return list[n];
        }
        return 1;
    }

这是一个非常缓慢的解决方案,但这似乎对我有用。

【问题讨论】:

  • 首先阅读您的代码并确定复杂性,例如O(1), O(logn), O(n!), ...,然后尝试在分析器下运行以查看“热点”(搜索 .NET 代码分析器。

标签: c# math sequence


【解决方案1】:

性能优化的第一条规则是衡量。理想情况下,使用可以告诉您大部分时间都花在哪里的分析器,但对于简单的情况,使用一些秒表就足够了。

我猜大部分时间会花在list.Contains,因为这是线性查找,并且在最里面的循环中。因此,一种方法是将列表更改为HashSet&lt;int&gt; 以提供更好的查找性能,跳过.Sort 调用,并返回hashSet 中的最大值。据我所知,应该给出相同的结果。

您也可以考虑使用一些比 .Net 中提供的通用容器更适合该问题的专用数据结构。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 2010-12-06
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多