How expensive is data templating? [closed]

匆匆过客 提交于 2019-12-14 02:02:27

问题


I have performance problems and I am trying to dig the reasons.

So far I am not sure what is the problem and my next assumption it's data templating. Question: how expensive is using data-templating?

Lets see how expensive is single data template. Below is mcve.

xaml:

<Window.Resources>
    <DataTemplate DataType="{x:Type local:Item}">
        <StackPanel>
            <TextBlock Text="{Binding Property1}" />

            ... we will add here more things to see difference
        </StackPanel>
    </DataTemplate>
</Window.Resources>
<ContentControl Content="{Binding Content}" />

cs:

class Item : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public string Property1 { get; set; } = "1";
    public string Property2 { get; set; } = "2";
    public string Property3 { get; set; } = "3";
    public string Property4 { get; set; } = "4";
    public string Property5 { get; set; } = "5";
}

class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public object Content { get; set; } = new Item();
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }
}

And here are some results (measured with VS profiler - application timeline in ms):

Test Nb Ni  Presenter    Items                         Bindings
A    1  1   2.42 (0.57)                                1.8
B    5  5   3.37 (1.15)                                1.8, 0.07, 0.1, 0.05, 0.08
C    5  10  3.63 (1.27)  0.06, 0.07, 0.08, 0.04, 0.04  1.7, 0.08, 0.05, 0.06, 0.05
D    0  1   3.38 (0.6)   2.7

Explanation:

  • Nb - number of bindings;
  • Ni - number of items (elements);
  • Presenter - time of ContentPresenter (total/self);
  • Items - items without binding times (when applicable);
  • Bidings - items with bindings times (when applicable).
  • A - is initial test, only one TextBlock with single Text binding.
  • B - added 4 more TextBlock to bind Text to other properties.
  • C - added 5 more TextBlock with static Text="123".
  • D - removed everything except 1 TextBlock with static text.

From what I can see, template itself takes 0.5 ms. There is a big cost for creating first item (why???).

To be honest I am not sure in correctness of this method to measure performance. Therefore my question. Should I avoid data-templating and start using old winforms way of populating controls manually to gain performance or what?

来源:https://stackoverflow.com/questions/38307477/how-expensive-is-data-templating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!