views:

819

answers:

2

Many types in WPF derive from Freezable. It provides immutability to mutable POCO objects and, apparently, allows for improved performance in certain situations.

Has anyone found that freezing objects within their WPF application has greatly improved performance? If so, then which items gave the biggest performance difference when being frozen?

(Note that I have posted a similar but different question too)

+2  A: 

These potential memory leaks could happen if you use the Image control (and not use Freeze method):

a) You use BitmapImage as the Image source and do not release the BitmapImage:

static BitmapImage bi1 = new BitmapImage(new Uri("Bitmap1.bmp",UriKind.RelativeOrAbsolute));
m_Image1 = new Image();
m_Image1.Source = bi1; 
//bi1.Freeze() 
//if you do not Freeze, your app will leak memory.
MyStackPanel.Children.Add(m_Image1);

b) You assign multiple BitmapImage as the Image source and do not release all of the BitmapImage you used (similar to (a)). This one introduced in .Net 3.5:

static BitmapImage bi1 = new BitmapImage(new Uri("Bitmap1.bmp",
UriKind.RelativeOrAbsolute));
static BitmapImage bi2 = new BitmapImage(new Uri("Bitmap2.bmp",
UriKind.RelativeOrAbsolute));
bi2.Freeze();
m_Image1 = new Image();
//bi1.Freeze() 
//even though you are really using bi2 for Image Source, 
//you also need to Freeze bi1 it to avoid leak 
m_Image1.Source = bi1;  // use un-frozen bitmap, which causes the leak
m_Image1.Source = bi2;  // use frozen bitmap
MyStackPanel.Children.Add(m_Image1);

Source: WPF Performance

M. Jahedbozorgan
+1  A: 

You might be interested in my experiences with Freezable:

I wrote a PDF viewer using muPdf which renders bitmaps, that I render with WPF. What helps performance greatly is that I can render the bitmaps on a background thread, freeze them, and pass them to the UI thread. It is also nice that WPF does not copy the image to freeze it, but the ability to do so from a background thread was the key benefit.

From what I understand, unfrozen visuals are always cloned to frozen ones, so they can be safely rendered by the render thread. It may be copied repeatedly due to WPF not knowing if the object is changed from the last time it was rendered. Frozen objects eliminate all this copying.

jdv