c# - 性能相交和不同的元素提取?

标签 c# .net optimization list intersection

我的代码中有如下一行:

potentialCollisionsX.Intersect(potentialCollisionsY).Distinct().ToList();

通过分析,我确定它占用了我大约 56% 的时间。我需要弄清楚如何提供有效的实现。我试过了

        List<Extent> probableCollisions = new List<Extent>();
        for (int j = 0; j < potentialCollisionsX.Count; j++)
        {
            if (potentialCollisionsY.Contains(potentialCollisionsX[j]) && !probableCollisions.Contains(potentialCollisionsX[j]))
            {
                probableCollisions.Add(potentialCollisionsX[j]);
            }
        }

但这只会将其降至 42%。非常感谢优化或替代想法。

编辑:有人要求提供有关 Extent 类的信息,我想不出比提供类定义更好的方式来向他们提供信息。

    private enum ExtentType { Start, End }
    private sealed class Extent
    {
        private ExtentType _type;
        public ExtentType Type
        {
            get
            {
                return _type;
            }
            set
            {
                _type = value;
                _hashcode = 23;
                _hashcode *= 17 + Nucleus.GetHashCode();
            }
        }
        private Nucleus _nucleus; //Nucleus is the main body class in my engine
        public Nucleus Nucleus
        {
            get
            {
                return _nucleus;
            }
            set
            {
                _nucleus = value;
                _hashcode = 23;
                _hashcode *= 17 + Nucleus.GetHashCode();
            }
        }

        private int _hashcode;

        public Extent(Nucleus nucleus, ExtentType type)
        {
            Nucleus = nucleus;
            Type = type;
            _hashcode = 23;
            _hashcode *= 17 + Nucleus.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            return Equals(obj as Extent);
        }
        public bool Equals(Extent extent)
        {
            if (this.Nucleus == extent.Nucleus) //nucleus.Equals does an int comparison
            {
                return true;
            }
            return false;
        }
        public override int GetHashCode()
        {
            return _hashcode;
        }
    }

Edit2:似乎使用哈希集可以使我的这部分代码达到我需要的性能,所以感谢您的帮助!

最佳答案

Intersect无论如何返回不同的元素,调用 Distinct()不必要。这至少会占用您的一些时间。

还有,你真的需要调用ToList吗? ?然后你对结果做了什么?

顺序重要吗?如果没有,您应该考虑使用 HashSet<T>而不是 List<T>对于您的“手动”代码。 (也可能为 HashSet<T> 创建一个 potentialCollisionsY。)这将使 Contains 成为调用速度更快,至少在集合足够大的情况下...

顺便说一句,不要相信documentation for Intersect - 这是 wrong about the order of operations (至少在 .NET 3.5 中)

关于c# - 性能相交和不同的元素提取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1679258/

相关文章:

c# - 在 asp.net 上使用 ajax 创建动态控件

c# - 处理和合并两个大文件

.net - 在 Webkit .NET 中打开本地文件

java - 在 Android OpenglEs 2.0 中加载纹理导致根本没有颜色

c# - 机器人模拟器调用/访问错误的消息 Controller

c# - 使用 LINQ 将常量字符串连接到 List<string> 中的每个项目

c# - MSBUILD 宏文档?

.net - OpenWrap 与 NuGet

javascript - 是什么使它成为在Web浏览器中打印1到1,000,000(以空格分隔)的最快的JavaScript?

c++ - 是否允许在 std::string 的实现中进行这种优化?