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 singleText
binding. - B - added 4 more
TextBlock
to bindText
to other properties. - C - added 5 more
TextBlock
with staticText="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?
ListBox
) will take minimum250 ms
to initialize. That's a lot.ListView
with several columns - and you run into same problem as I do. – Maraschino