What is the reason behind this huge Performance difference in .Net 4

后端 未结 4 1786
花落未央
花落未央 2021-01-31 05:40

I was just doing some research on RedBlack Tree. I knew that SortedSet class in .Net 4.0 uses RedBlack tree. So I took that part out as is using Reflector and created a RedBlack

4条回答
  •  我在风中等你
    2021-01-31 05:50

    You have a bug in your Node class. When you call the constructor that only takes a single value argument you should be setting IsRed to true.

    I suppose that the fixed Node class should look something like this:

    public sealed class Node
    {
        public T Item { get; private set; }
        public bool IsRed { get; set; }
        public Node Left { get; set; }
        public Node Right { get; set; }
    
        public Node(T value)
        {
            Item = value;
            IsRed = true;
        }
    
        public Node(T value, bool isRed)
        {
            Item = value;
            IsRed = isRed;
        }
    }
    

    Another option -- my preference -- would be to omit that constructor altogether and always require IsRed to be set explicitly when you instantiate a new node:

    public sealed class Node
    {
        public T Item { get; private set; }
        public bool IsRed { get; set; }
        public Node Left { get; set; }
        public Node Right { get; set; }
    
        public Node(T value, bool isRed)
        {
            Item = value;
            IsRed = isRed;
        }
    }
    

    And then replace this line in your Add method...

    Node current = new Node(item);
    

    ...with this...

    Node current = new Node(item, true);
    

提交回复
热议问题