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

后端 未结 4 1741
花落未央
花落未央 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<T> 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<T> class should look something like this:

    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;
        }
    }
    

    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<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;
        }
    }
    

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

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

    ...with this...

    Node<T> current = new Node<T>(item, true);
    
    0 讨论(0)
  • 2021-01-31 05:51

    SortedSet includes a TargetedPatchingOptOut attribute, did your copied version include that?

    [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
    public bool Add(T item)
    {
        return this.AddIfNotPresent(item);
    }
    
    0 讨论(0)
  • 2021-01-31 05:54

    If the difference wasn't that big I would suggest that the cause is that the .NET assemblies are NGen-ed and so they are already translated to native code. In the case of your class the time to compile the IL code into native code is amortized over the time of your test. How does increasing the number of loop iterations affect the times?

    0 讨论(0)
  • 2021-01-31 05:55
    1. reverse the order of the tests and repeat the measurement.
    2. randomize your data. Sorted sets behave strangely when you insert pre-sorted data.
    0 讨论(0)
提交回复
热议问题