不指定控件名称在WPF ...性能效果 [英] Not specifying control names in WPF... performance effect

查看:113
本文介绍了不指定控件名称在WPF ...性能效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您需要从代码中访问WPF控件,则需要在XAML中提供 Name 属性。

If you need to access a WPF control from the code behind, you need to supply a Name attribute to it in XAML.

在很多情况下,你不需要从后面的代码访问控制,因为很多编码逻辑,如绑定更好地直接应用于XAML。

In many cases, you don't need to access controls from the code behind, since a lot of coding logic such as binding is better applied directly inside XAML.

我的问题是:从提供名称属性到控件有性能增益吗?

My question is: Is there a performance gain from not supplying the name attribute to controls? Or is it a good habit to give names to all controls on the page?

推荐答案

是的,从某种程度上来说,提供名称属性。

Yes there is definitely a performance gain from not supplying "name" attributes.

WPF的名称机制可能很有用,但它以多种方式使用额外的RAM和CPU:

WPF's "Name" mechanism can be useful, but it uses extra RAM and CPU in several ways:


  1. XAML编译器在每个命名对象的类中分配一个额外的槽(每个4字节)

  2. XAML编译器

  3. BAML处理器还会将名称添加到一个字典,每个名字需要额外20个字节

  4. 查找名字时,你真的需要你可能遇到字典碰撞与你真正需要的名称

  1. The XAML compiler allocates an extra slot in your class for every named object (4 bytes each)
  2. The XAML compiler adds code to your class to initate each of these
  3. The BAML processor calls back your code to initialize the name in each case
  4. The BAML processor also adds the name to a dictionary, requiring an additional 20+ bytes per name
  5. When looking up names you really need you may run into dictionary collisions with names you don't really need

对于简单控件,向控件添加名称可以将使用该控件的成本增加5%左右。这不是很多,但为什么浪费你的CPU周期和你的RAM上的名字是不必要的?

For a simple control, adding a Name to control can increase the cost of using that control by 5% or so. That's not a lot, but why waste your CPU cycles and your RAM on names that are unnecessary?

底线:如果你不需要名称对象,不要命名他们。通常,控件的内容或约束足以识别控件的用途。如果这不是足够的文档,你总是可以使用XML注释,这是免费的。

Bottom line: If you don't need Names on your objects, don't name them. Usually the content or binding of a control is plenty to identify a control's purpose. And if that isn't enough documentation, you can always use XML comments, which are free.

我不得不说这是一个非常 / strong>习惯来命名所有的控件,不仅仅是因为成本,还因为它鼓励你按名称引用你的控件,而不是使用合适的视图模型和绑定技术。我的大多数XAML不会对任何控件使用名称,更不用说所有的控件。

I'd have to say it is a very bad habit to name all your controls, not just because of the cost but also because it encourages you to refer to your controls by name rather than using proper view model and binding techniques. Most of my XAML doesn't use "Name" for any controls, let alone all of them.

这篇关于不指定控件名称在WPF ...性能效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆