【发布时间】:2017-08-26 06:01:31
【问题描述】:
所以我有一个 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。 这有关系吗?性能差异是否显着?
【问题讨论】:
-
几乎肯定不足以覆盖任何其他因素,例如可读性或灵活性。
-
a) 在 WPF 应用程序中,这几乎肯定不会很重要。任何潜在的差异都可能是处理量的千分之一与写入流或执行字符串操作的行为相比,以及刷新 UI 成本的百万分之一。 b) 如果这些在您构建发布时有效地生成相同的 IL 代码,我不会感到特别惊讶。
-
您正在编写 WPF 应用程序,而不是一些低级硬件驱动程序。 WPF 所做的任何事情都会比这花费更多的时间。但是,如果属性不是简单的
{get;set;},而是在 getter 中发生了一些重要的事情 - 那么第二种方式会更好。 -
如果你想知道有什么区别,请测量它。你有两个程序。
-
循环 1000 万次(不写入控制台),示例 1 大约是 5.5 秒,示例 2 在我的机器上大约是 5.1 秒。我很好奇
标签: c# dot-operator