【问题标题】:What is the reason behind this huge Performance difference in .Net 4.Net 4 中这种巨大的性能差异背后的原因是什么
【发布时间】:2011-04-12 13:15:46
【问题描述】:

我只是在对 RedBlack Tree 进行一些研究。我知道 .Net 4.0 中的 SortedSet 类使用 RedBlack 树。所以我像使用 Reflector 一样把这部分拿出来,并创建了一个 RedBlackTree 类。现在我在这个 RedBlackTree 和 SortedSet 上运行一些性能测试,插入 40000 个连续的整数值(从 0 到 39999),我很惊讶地发现性能差异很大,如下所示:

 RBTree    took 9.27208   sec to insert 40000 values 
 SortedSet took 0.0253097 sec to insert 40000 values

这背后的原因是什么?顺便说一句,我只在发布配置中运行了测试,这里是小测试代码

            var stopWatch = new Stopwatch();
            var rbT = new RedBlackTree<int>();      
        stopWatch = new Stopwatch();
        stopWatch.Start();
        for (int i = 0; i < 40000; i++) {
            rbT.Add(i);
        }
        stopWatch.Stop();
        Console.WriteLine(stopWatch.Elapsed);

        var ss = new SortedSet<int>();
        stopWatch = new Stopwatch();
        stopWatch.Start();
        for (int i = 0; i < 40000; i++) {
            ss.Add(i);
        }
        stopWatch.Stop();
        Console.WriteLine(stopWatch.Elapsed);

编辑

我还想分享我提取的 RBTree 代码,以便您也可以运行诊断程序

public class Node<T>
    {
        public Node(){}

        public Node(T value)
        {
            Item = value;
        }       

        public Node(T value, bool isRed)
        {
            Item = value;
            IsRed = isRed;
        }

        public T Item;
        public Node<T> Left;
        public Node<T> Right;
        public Node<T> Parent;
        public bool IsRed;
    }

    public class RedBlackTree<T>
    {
        public RedBlackTree(){} 

        public Node<T> root;
        int count, version; 
        Comparer<T> comparer = Comparer<T>.Default;     

        public void Add(T item)
        {
            if (this.root == null)
            {
                this.root = new Node<T>(item, false);
                this.count = 1;
                this.version++;
                return;
            }

            Node<T> root = this.root;
            Node<T> node = null;
            Node<T> grandParent = null;
            Node<T> greatGrandParent = null;
            this.version++;

            int num = 0;
            while (root != null)
            {
                num = this.comparer.Compare(item, root.Item);
                if (num == 0)
                {
                    this.root.IsRed = false;
                    return;
                }
                if (Is4Node(root))
                {
                    Split4Node(root);
                    if (IsRed(node))
                    {
                        this.InsertionBalance(root, ref node, grandParent, greatGrandParent);
                    }
                }
                greatGrandParent = grandParent;
                grandParent = node;
                node = root;
                root = (num < 0) ? root.Left : root.Right;
            }
            Node<T> current = new Node<T>(item);
            if (num > 0)
            {
                node.Right = current;
            }
            else
            {
                node.Left = current;
            }
            if (node.IsRed)
            {
                this.InsertionBalance(current, ref node, grandParent, greatGrandParent);
            }
            this.root.IsRed = false;
            this.count++;
        }


        private static bool IsRed(Node<T> node)
        {
            return ((node != null) && node.IsRed);
        }

        private static bool Is4Node(Node<T> node)
        {
            return (IsRed(node.Left) && IsRed(node.Right));
        }

        private static void Split4Node(Node<T> node)
        {
            node.IsRed = true;
            node.Left.IsRed = false;
            node.Right.IsRed = false;
        }

        private void InsertionBalance(Node<T> current, ref Node<T> parent, Node<T> grandParent, Node<T> greatGrandParent)
        {
            Node<T> node;
            bool flag = grandParent.Right == parent;
            bool flag2 = parent.Right == current;
            if (flag == flag2)
            {
                node = flag2 ? RotateLeft(grandParent) : RotateRight(grandParent);
            }
            else
            {
                node = flag2 ? RotateLeftRight(grandParent) : RotateRightLeft(grandParent);
                parent = greatGrandParent;
            }
            grandParent.IsRed = true;
            node.IsRed = false;
            ReplaceChildOfNodeOrRoot(greatGrandParent, grandParent, node);
        }

        private static Node<T> RotateLeft(Node<T> node)
        {
            Node<T> right = node.Right;
            node.Right = right.Left;
            right.Left = node;
            return right;
        }

        private static Node<T> RotateRight(Node<T> node)
        {
            Node<T> left = node.Left;
            node.Left = left.Right;
            left.Right = node;
            return left;
        }

        private static Node<T> RotateLeftRight(Node<T> node)
        {
            Node<T> left = node.Left;
            Node<T> right = left.Right;
            node.Left = right.Right;
            right.Right = node;
            left.Right = right.Left;
            right.Left = left;
            return right;
        }

        private static Node<T> RotateRightLeft(Node<T> node)
        {
            Node<T> right = node.Right;
            Node<T> left = right.Left;
            node.Right = left.Left;
            left.Left = node;
            right.Left = left.Right;
            left.Right = right;
            return left;
        }

        private void ReplaceChildOfNodeOrRoot(Node<T> parent, Node<T> child, Node<T> newChild)
        {
            if (parent != null)
            {
                if (parent.Left == child)
                {
                    parent.Left = newChild;
                }
                else
                {
                    parent.Right = newChild;
                }
            }
            else
            {
                this.root = newChild;
            }
        }
    }

编辑


我对其他一些数据结构(一些由我创建*,一些来自 .net 框架**)进行了相同的诊断,这是有趣的结果

*AATree                 00:00:00.0309294
*AVLTree                00:00:00.0129743
**SortedDictionary      00:00:00.0313571
*RBTree                 00:00:09.2414156
**SortedSet             00:00:00.0241973

RBTree 与上面相同(从 SortedSet 类中删除)。 我也尝试了 400000 个值,但 RBTree 似乎永远占用了,我真的不知道为什么。

【问题讨论】:

  • 您是否尝试过使用分析器来找出您的代码花费最多时间的位置?
  • 当你说你在发布配置中“运行”了测试——是在调试器里面吗?还是在平面命令提示符下?
  • 如果您的代码以相反的顺序执行,是否仍然会发生这种情况,例如先SortedSet,后RBTree?
  • 我怀疑 JIT。像 ChrisBD 说的那样以相反的顺序运行它,或者运行几次,而不是一次(我的意思是把代码放在一个循环中,以便它在同一个程序执行中运行多次)
  • @Choco,如果 JIT 需要 9 秒我们就不会使用 .NET

标签: c# .net data-structures performance red-black-tree


【解决方案1】:

你的Node&lt;T&gt; 类中有一个错误。当您调用仅采用单个值参数的构造函数时,您应该将 IsRed 设置为 true。

我想固定的Node&lt;T&gt; 类应该是这样的:

public sealed class Node<T>
{
    public T Item { get; private set; }
    public bool IsRed { get; set; }
    public Node<T> Left { get; set; }
    public Node<T> Right { get; set; }

    public Node(T value)
    {
        Item = value;
        IsRed = true;
    }

    public Node(T value, bool isRed)
    {
        Item = value;
        IsRed = isRed;
    }
}

另一个选项——我的偏好——是完全省略该构造函数,并且在实例化新节点时始终要求显式设置 IsRed:

public sealed class Node<T>
{
    public T Item { get; private set; }
    public bool IsRed { get; set; }
    public Node<T> Left { get; set; }
    public Node<T> Right { get; set; }

    public Node(T value, bool isRed)
    {
        Item = value;
        IsRed = isRed;
    }
}

然后在您的 Add 方法中替换这一行...

Node<T> current = new Node<T>(item);

...用这个...

Node<T> current = new Node<T>(item, true);

【讨论】:

  • 哦!你这个人。我只是更改了它并运行了诊断程序并猜测现在的响应时间是多少 - 同一组数据的响应时间为 00.0204438 秒。非常感谢,你节省了一天。
  • 太棒了。包括我在内的很多人都在猜测 NGen、逆序、编译问题……而且它似乎来自代码 :)
  • 在这种情况下,很难指出。更便宜(最重要的选择)总是与环境有关。但是 IMO 首先应该检查代码,以防出现如此惊人的性能差异或其他类型的完全出乎意料的结果。我有过类似的经验,遇到代码并纠正代码问题总是正确的!
  • 这也是奥卡姆剃刀原理的一个很好的例子。 “它指出,在相互竞争的假设中,应选择假设最少的假设。”
【解决方案2】:
  1. 颠倒测试顺序并重复测量。
  2. 随机化您的数据。当您插入预先排序的数据时,排序集的行为会很奇怪。

【讨论】:

  • 你是对的!随机化数据给出可比较的结果。性能差异可以忽略不计。但我在这里谈论的是最坏的情况。为什么在这种特殊情况下,当 RBTree 本身实现 SortedList 时,这两者的行为会有所不同?
  • 所以它们是两种完全不同的算法。又是一场鹅追逐。
【解决方案3】:

SortedSet 包含TargetedPatchingOptOut 属性,您复制的版本是否包含该属性?

[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public bool Add(T item)
{
    return this.AddIfNotPresent(item);
}

【讨论】:

  • 与性能无关。从 MSDN 开始,它表明应用此属性的 .NET Framework 类库方法不太可能受到服务版本的影响,因此可以跨原生图像生成器 (NGen) 图像内联。
  • 我怀疑性能差异是由于跨原生图像生成器 (NGen) 图像的方法内联造成的。
  • @Anindya Chatterjee - 方法很小,因此内联它们可以在性能中发挥重要作用。
【解决方案4】:

如果差异不是那么大,我建议原因是 .NET 程序集是 NGen 版的,因此它们已经被翻译为本机代码。对于您的课程,将 IL 代码编译为本机代码的时间将在您的测试时间中摊销。增加循环迭代次数对时间有何影响?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2021-11-01
    • 2021-04-02
    • 2017-11-23
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多