Thursday, August 25, 2011

Where XNA beats up Silverlight

   Finally a blog post. I am in the process of updating (it's more of a rewriting) Boxfiles for Mango. Till now I have rewritten the Dropbox library from scratch (took off all the dependencies Hammock, Json.Net and now it's pure HttpWebRequest) and developed a library for accessing Skydrive resources (it works and it is possible to list the folders and download the files mainly what I need to get the modified Office files back to Dropbox). Anyway the Skydrive API it's a mess for the moment and I really hope they will get a "clean" API. The current version of the Rest Api is usable only for contacts, photos and videos. I will post both libraries on Codeplex (very probable after I finish the update of Boxfiles). 
    So what is this post all about. One of the features of the new version of Boxfiles will be pinch to zoom. Searching on the web I have found the XNA and the Silverlight solutions. I've started with Silverlight and with pinch to zoom added the application would easily eat more than 90MB of RAM while the image window is opened.  Digging up on what was consuming so much memory it turned up that the image window eats around 40 MB of memory (also because I have enabled CacheMode="BitmapCache" in order to have a smooth zoom). This is an abomination for a simple page with one menu and an Image control displaying a file  of 3MB. I than remembered that, in Mango, Silverlight and Xna can "live" together. The feature was introduced for enabling Silverlight in Xna (menus and stuff) , but in this particular case I will use Xna in Silverlight. I've created a project where I can compare the pinch to zoom on both Xna and Silverlight. The results are not bad: XNA uses around 10MB while Silverlight uses 40MB and the pinch to zoom is much smoother in Xna (the sample starts with 10MB of memory occupied).




    In order to have a realistic comparison I've added an ApplicationBar to the Xna window and both of the windows have a Menu where you can force the GC to collect. While testing the solution I've found a really strange behavior (in my opinion it's a memory leak of the image control and maybe somebody from Microsoft should have a look into it): the Silverlight window, after the first launch, was not releasing 10MB of memory. In order to release the memory I had to manually remove the Image control from the ContentPanel and give it a null value.


ContentPanel.Children.Remove(image);
image = null;

If you play with the solution just comment the two lines located in OnNavigatedFrom (ImageSilverlight.xaml.cs) and you will see the leak.

Here is the Source Code

NAMASTE!