Windows Phone performance analysis & optimization during TechDays

.Net, Silverlight, Windows Phone No Comments »

In about 2 weeks now, I’ll have the chance to be part of the French TechDays in Paris as a speaker. This year, I’ll own a session called “Windows Phone performance analysis & optimisation” with my colleague Charlotte.

The agenda looks like the following:

  • why performance analysis ?
  • device vs emulator
  • leveraging WP7 threads
  • using the VS profiler for WP7
  • tips and tricks

During the session we will use a “real” app we’re working on for a few months now (I’ll share more details after the session). We have some cool tips that haven’t been shared anywhere before, so if performance is a topic of interest for you, stat tuned !

Click on the following image for a link to the TechDays website:

I’m planning to share the most of the content of this session on my blog soon after the event.

Don’t hesitate to stop by and say hi…

Track memory usage of your Windows Phone 7.1 app in real time

Windows Phone 1 Comment »

Update January 17th: I just found out that Peter Torr released more than a year ago a similar helper class which is very nice. You can check out his solution here.

Memory usage is an important aspect, especially on mobile device. If you want to publish an app on the Windows Phone marketplace you must satisfy the Technical Certification Requirements: “5.2.5 Memory Consumption: An application must not exceed 90 MB of RAM usage, except on devices that have more than 256 MB of memory.”

In this post, I’m sharing a technique to track the memory usage of a WP7 app in real tile in every single page of the app. By adding only one line of code in your existing app, you’ll be able to display memory usage in all your pages (without any changes):

Download source code and example

How to integrate the component in your existing app?

  1. import the MemoryWatcher class in your existing project
  2. in the InitializePhoneApplication method, add a new line after the creation of the RootFrame:
?View Code CSHARP
1
2
3
4
5
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
// Add the following line !
new MemoryWatcher(RootFrame) { IsDisplayed = true };

How it works?

During its initialization, the MemoryWatcher control will set an event handler to have a callback whenever the user navigates to a new page. When the new page is loaded, it checks if it can dynamically insert the MemoryWatcher control. This is done by checking the root UI element of the page and inserting the watcher control in it. Here is the full code of the MemoryWatcher class:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Threading;
 
using Microsoft.Phone.Controls;
using Microsoft.Phone.Info;
 
namespace MemoryWatcherDemo
{
    public class MemoryWatcher : ContentControl
    {
        private readonly DispatcherTimer timer;
        private readonly PhoneApplicationFrame frame;
        private const float ByteToMega = 1024 * 1024;
 
        public bool IsDisplayed { get; set; }
 
        public MemoryWatcher(PhoneApplicationFrame frame)
        {
            if (frame == null)
                throw new ArgumentNullException("frame");
 
            this.frame = frame;
            this.frame.Navigated += new NavigatedEventHandler(this.OnFrameNavigated);
            this.frame.Navigating += new NavigatingCancelEventHandler(this.OnFrameNavigating);
 
            this.timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) };
            this.timer.Tick += new EventHandler(this.OnTimerTick);
 
            // setup some basic properties to ensure the content will be visible
            this.Foreground = new SolidColorBrush(Colors.Red);
            this.VerticalContentAlignment = VerticalAlignment.Center;
            this.HorizontalContentAlignment = HorizontalAlignment.Center;
            this.Margin = new Thickness(0, -35, 0, 0);
        }
 
        private void OnFrameNavigated(object sender, NavigationEventArgs e)
        {
            if (!this.IsDisplayed)
                return;
 
            var page = this.frame.Content as PhoneApplicationPage;
            if (page != null)
            {
                Panel host = page.Content as Panel;
                if (host != null && !host.Children.Any(c => c is MemoryWatcher))
                {
                    this.timer.Start();
                    host.Children.Add(this);
                }
            }
        }
 
        private void OnFrameNavigating(object sender, NavigatingCancelEventArgs navigatingCancelEventArgs)
        {
            var page = this.frame.Content as PhoneApplicationPage;
            if (page != null)
            {
                Panel host = page.Content as Panel;
                if (host != null && host.Children.Contains(this))
                {
                    this.timer.Stop();
                    host.Children.Remove(this);
                }
            }
        }
 
        private void OnTimerTick(object sender, EventArgs e)
        {
            try
            {
                string currentMemory = (DeviceStatus.ApplicationCurrentMemoryUsage / ByteToMega).ToString("#.00");
                string peakMemory = (DeviceStatus.ApplicationPeakMemoryUsage / ByteToMega).ToString("#.00");
 
                this.Content = string.Format("Current: {0}MB Peak: {1}MB", currentMemory, peakMemory);
            }
            catch (Exception)
            {
                this.timer.Stop();
            }
        }
    }
}

Note:

  • The MemoryWatcher is looking for a Panel type in order to add itself to the list of children in the page. You might want to modify and improve this portion in order to better fit your needs.
  • The attached project targets Windows Phone 7.1, if you want to use the code in a 7.0 version, you should change the way the memory values are read (see this article for more details)

Enjoy the code and start tracking memory leaks :-)

Download source code and example

 

How to measure rendering time in a WPF application ?

WPF 2 Comments »

Last week, a colleague of mine asked me an interesting question: “I’m filling a control with content and I’d like to measure the time needed to render my control. How can I do that ?”

The first approach is to measure the elapsed time needed to instantiate and populate the control from C# code. We can use the StopWatch class to have a precise and easy to use measuring tool.

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
Stopwatch sw = new Stopwatch();
sw.Start();
 
for (int i = 0; i < 5000; i++)
{
  // here is the operation that fills the control
  this.canvas.Children.Add(new Rectangle());
}
 
sw.Stop();
MessageBox.Show("Took " + sw.ElapsedMilliseconds + " ms");

However this approach will not give good results because we’re not taking into account the time needed to render elements in the visual tree. This is because elements are not rendered when you call the Add methods (for example in a Canvas) but when the visual tree is fully loaded.

A much better approach is to use the Dispatcher and request it to process an action at a priority right bellow the Render priority which is the Loaded priority:

dispatcherpriority

Using this trick, we ensure that all rendering actions have been completed. We can use the following code to do that:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Stopwatch sw = new Stopwatch();
sw.Start();
 
for (int i = 0; i < 5000; i++)
{
  // here is the operation that fills the control
  this.canvas.Children.Add(new Rectangle());
}
 
this.Dispatcher.BeginInvoke(
  DispatcherPriority.Loaded,
  new Action(() =>
  {
    sw.Stop();
    MessageBox.Show("Took " + sw.ElapsedMilliseconds + " ms");
  }));

Hope this helps !

The cost of building Visual Trees

.Net, WPF No Comments »

In the current project I’m working on, I’m designing a diagramming component. Of course because it’s for work I can’t release the source code (however if you want a good starting point you can check out this article). Designing such a component is a challenging task and there are a number of things I learned during the last few months that I’m glad to share here.

As you problably know the WPF engine manages 2 trees: the logical tree and the visual tree. For each logical item (that you declare in the XAML), the item is expanded with its visual tree (for example, a scrollbar is made of RepeatButtons and a Thumb). To visualize the visual tree you can use a tool like snoop.

In a diagramming tool, you might want to draw lines betweeen entities, like the following:

connection

In this article, we’re going to talk about the underlying control that we can use to do that. If you need to create that kind of control, you basically have 2 options:

  • inherits from Control and override the OnRender method to do the basic graphic operations (such as drawing a line or an ellipse)
  • inherits from Control and create a ControlTemplate to fill the visual tree of your control

Of course the first option has better performance, but it’s also less evolutive. Moreover, in the OnRender method, you can only do low level graphic operations.

Using the second option is generally fine and easy:

  1. create the class that inherit from Control
  2. create a style that targets your new control
  3. add a Setter to set the ControlTemplate property
  4. fill the ControlTemplate’s content

Here is a sample ControlTemplate for a basic connection (assuming that the Connection class has 4 double dependency properties (X1,Y1) (X2,Y2) that defines that start and the end point):

1
2
3
4
5
6
7
8
9
10
11
12
<Style TargetType="{x:Type VisualTreePerf:Connection}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type VisualTreePerf:Connection}">
          <Line X1="{TemplateBinding X1}" Y1="{TemplateBinding Y1}"
                  X2="{TemplateBinding X2}" Y2="{TemplateBinding Y2}"
                  Stroke="Black" StrokeThickness="2">                                
          </Line>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Of course this is a very minimal template, you’re probable going to improve it by adding new features:

  • 2 rectangles to show the extremities of the connection
  • 2 thumb to be able to drag’n'drop the extremities
  • 1 context menu to access connection’s operations

You can do that by adding more controls to the template. Now, take a second and think about the performances. Time is needed to built and render the visual tree and the most complex it is, the longer it takes. I did a quick benchmark on my machine and here are the results for 500 connections added in a Canvas:

performance

What we can see is that adding only 5 controls in the template, we multiply the rendering time by 4 ! That means we must be careful when we’re designing ControlTemplate that are going to be instantiated many time. Before creating the control we should think about whether the control is going to by displayed 1, 10, 100 or 1000 times in our application. More complex ControlTemplates mean more time to render them. Several techniques can be used to improved performance:

  • use a panel that supports UI virtualization (such a VirtualizingStackPanel)
  • use adorners to give feedback while an item is selected to improve creation performance (create the Adorner only when the item is selected)

To explore other performance related techniques:

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in