As I mentioned in a previous post, you can quite easily load Xaml dynamically in your Xamarin.Forms App. But how about performance? How long does it take in comparison to “regular” loading of pre-compiled Xaml.
It’s anything but easy to really measure this. We could eventually use LoadFromXaml and measure the differences. I decided to create DataTemplates and use the CreateContent() method to create the actual Control.
<DataTemplate x:Key="Test1">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Text="Hello World!" />
<Button Grid.Row="1" Text="Press me" />
</Grid>
</DataTemplate>
<DataTemplate x:Key="Test2">
<dynamiccontrol:XamlView>
<dynamiccontrol:XamlView.Xaml>
<![CDATA[
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Text="Hello World!" />
<Button Grid.Row="1" Text="Press me" />
</Grid>
]]>
</dynamiccontrol:XamlView.Xaml>
</dynamiccontrol:XamlView>
</DataTemplate>
You can see that the Xaml is quite easy, but loading it dynamically takes over 20 times longer than compiled Xaml.
I tried to create 10,000 controls and measured the following values:
Compiled Xaml: 5.8s
Dynamic Xaml: 133.1s
I know the test is not very representative, but you should always keep in mind that there may be a performance problem when using this method. Especially when you want to create dynamic Layouts in ListViews.
You can slightly boost performance (5-10%), when you load the whole DataTemplate from Xaml, and then create the Control with it.
Dynamic DataTemplate: 124s