Search code examples
c#dot-operator

c# dot operator overhead: What is more efficient


So I have a WPF application that has a base MVVM with child MVVMs. I tried googling the answer but wasn't sure of the technical terms so I will provide two examples below and perhaps someone can give me a little insight into the efficiency of the examples. I want to know if there is little difference in the overhead or significant.

Lets say I have a setup similar to the following

public class ParentViewModel
{
    public ParentViewModel()
    {
        Child = new ChildViewModel();
    }

    public ChildViewModel Child { get; set; }
}

public class ChildViewModel
{
    public ChildViewModel()
    {
        GrandChild = new GrandChildViewModel();
    }

    public GrandChildViewModel GrandChild { get; set; }
}

public class GrandChildViewModel
{
    public GrandChildViewModel()
    {
        GreatGrandChild = new GreatGrandChildViewModel();
    }

    public GreatGrandChildViewModel GreatGrandChild { get; set; }
}

public class GreatGrandChildViewModel
{
    public GreatGrandChildViewModel()
    {
         intA = 1;
         intB = 2;
         intC = 3;
    }

    public int intA { get; set; }
    public int intB { get; set; }
    public int intC { get; set; }
}

And the following two examples of usage is where I want the insight.

Example 1:

public Main()
{
     var parent = new ParentViewModel();

     Console.WriteLine($"A: {parent.Child.GrandChild.GreatGrandChild.intA}" +
                       $"B: {parent.Child.GrandChild.GreatGrandChild.intB}" +
                       $"C: {parent.Child.GrandChild.GreatGrandChild.intC}");
}

Example 2:

public Main()
{
     var greatGrandChild = new ParentViewModel().Child.GrandChild.GreatGrandChild;

     Console.WriteLine($"A: {greatGrandChild.intA}" +
                       $"B: {greatGrandChild.intB}" +
                       $"C: {greatGrandChild.intC}");
}

Which one is more efficient? I'm asking because I would think Example 2 would be more efficient as it goes down to the lowest level once and then accesses intA, intB, and intC. Does this matter? Is the difference in performance significant?


Solution

  • You will notice absolutely no optimization between the two. In fact, I suspect the compiler would optimize both types of statement into the same IL.

    The latter example is more readable, however, so I'd opt for that approach.