views:

38

answers:

1

If you need to access a WPF control from the code behind, you need to supply a Name attribute to it in 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?

+3  A: 

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

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

  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

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?

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.

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.

Ray Burns