所以我有一个 WPF 应用程序,它有一个带有子 MVVM 的基本 MVVM。我尝试用谷歌搜索答案,但不确定技术术语,所以我将在下面提供两个示例,也许有人可以让我对示例的效率有所了解。我想知道开销是否有很小的差异或显着。
假设我有一个类似于以下的设置
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; }
}
以下两个使用示例是我想要了解的地方。
示例 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}");
}
示例 2:
public Main()
{
var greatGrandChild = new ParentViewModel().Child.GrandChild.GreatGrandChild;
Console.WriteLine($"A: {greatGrandChild.intA}" +
$"B: {greatGrandChild.intB}" +
$"C: {greatGrandChild.intC}");
}
哪个效率更高?我之所以问,是因为我认为示例 2 会更有效,因为它会下降到最低级别一次,然后访问 intA、intB 和 intC。这有关系吗?性能差异是否显着?