Compare performace of WPF Converters, DataTriggers and Direct Binding

By | October 21, 2013

Advertisement from Google

Hello,

I have made some performance tests with DataTriggers and Converters. For testing purposes I have chosen Visibility property. In first case I have binded Visibility property to IsVisible view model boolean property with standard BooleanToVisibilityConverter converter.

<Border Visibility="{Binding IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}" Background="Blue" />

Next case was written with DataTrigger

<Border Background="Red">
  <Border.Style>
    <Style TargetType="Border">
      <Setter Property="Visibility" Value="Visible" />
      <Style.Triggers>
        <DataTrigger Binding="{Binding IsVisibleDataTrigger}" Value="False">
          <Setter Property="Visibility" Value="Collapsed" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Border.Style&
</Border>

And the last one is the simple binding to Visibility view model property of System.Windows.Visibility type:

<Border Visibility="{Binding Visibility}" Background="Green" />

Advertisement from Google

To test all cases I have run following code in separate thread:

await Task.Factory.StartNew(
() =>
  {
    int N = 1000000;
    Stopwatch timer = new Stopwatch();
    timer.Start();
    for (int i = 0; i < N; i++)
    {
      viewModel.IsVisible = !viewModel.IsVisible;
    }

    timer.Stop();
    resultConveter = timer.ElapsedMilliseconds;

    timer.Reset();
    timer.Start();
    for (int i = 0; i < N; i++)
    {
      viewModel.IsVisibleDataTrigger = !viewModel.IsVisibleDataTrigger;
    }

    timer.Stop();
    resultDataTrigger = timer.ElapsedMilliseconds;

    timer.Reset();
    timer.Start();
    bool isVisible = viewModel.Visibility == Visibility.Visible;
    for (int i = 0; i < N; i++)
    {
      viewModel.Visibility = isVisible ? Visibility.Collapsed : Visibility.Visible;
      isVisible = !isVisible;
    }

    timer.Stop();
    resultBinding = timer.ElapsedMilliseconds;
  });

Here is results of this testing (lower is better):

dia

 

As we can see Binding is the fastest, but by using converters with boolean view model property you will make you view model code cleaner.

 

One thought on “Compare performace of WPF Converters, DataTriggers and Direct Binding

  1. Andrew

    When I read this article I thought that its obvious. But today I met performance issue in my code, remembered this article and it became helpful 🙂

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *