Category: Code Optimization

Home / Category: Code Optimization

There are many ways to write an app and many patterns to follow. Some are very useful, others a bit less but there is one that you should always use MVVM, Model View View Model. It allows you to separate your apps in three main parts or layers:

Model: Your data

View: Your UI

View Model: Your logic

This pattern is brilliant so you should really use it. In it, your View knows nothing about the logic of your app and your ViewModel knows nothing about the UI, but they communicate through a mechanism called Data Binding.

<Label Text="{Binding MyTitle}"/>

In this quick example we have associated the text property of our Label to the property “MyTitle” in our ViewModel. Easy, isn’t it?


The problem

MVVM is great (and you should really use it) BUT the data binding has two big problems:

  • Because they are resolved at run-time, you have no validation at compile-time. It means that if in the previous example, instead of MyTitle you write MyTile, you code will compile fine and you will be able to run your app BUT you will not see the text in your label.
  • As we said, they are resolved at run-time through a mechanism called reflection. Reflection is cool but it has an high overhead cost, so every time you load a page with some bindings, your app will consume time.

The solution

Luckily there is a solution to enjoy MVVM and Data Binding, without having to worry about performances and the solution is Compiled Bindings.

To enable the Compiled Binding you have to do two quick steps:

  • Enable XAML compilation.
  • Set the correct x:DataType attributes.

It’s incredibly easy to do it an it’s easier to do that to explain so I’m going to show you how to do it with an example.


If you are starting a new Xamarin.Forms project, the template already has the XAML compilation enabled, but if you need to enable it you can add this attribute:

[XamlCompilation(XamlCompilationOptions.Compile)]

to your page class in your XAML code behind. So the class of your page will be similatr to this:

[XamlCompilation (XamlCompilationOptions.Compile)]
public class HomePage : ContentPage
{
    //Add your content here...
}

Very easy. Now let’s see how to set the correct x:DataType.

First of all, let’s say that our View is called MyExamplePage and our ViewModel is called MyExampleViewModel and that our page has a label with a binding:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:viewModels="clr-namespace:XamarinExpert.ViewModels;assembly=XamarinExpert"
             x:Class="XamarinExpert.Views.MyExamplePage">
    <ContentPage.BindingContext>
        <viewModels:MyExampleViewModel />
    </ContentPage.BindingContext>
    <ContentPage.Content>
        <StackLayout>
            <Label Text="{Binding MyTitle}"
                VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

This is a perfectly correct XAML and if we build and start it, it will run. If the property MyTitle exists in MyExampleViewModel, then we will be able to see the text.

Now let’s add the x:DataType  to enable the Compiled Data Binding. The code will be:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:viewModels="clr-namespace:XamarinExpert.ViewModels;assembly=XamarinExpert"
             x:DataType="viewModels:MyExampleViewModel"
             x:Class="XamarinExpert.Views.MyExamplePage">
    <ContentPage.BindingContext>
        <viewModels:MyExampleViewModel />
    </ContentPage.BindingContext>
    <ContentPage.Content>
        <StackLayout>
            <Label Text="{Binding MyTitle}"
                VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

the only thing we have added is:

x:DataType="viewModels:MyExampleViewModel"

I told you that it was easy.

Now we have obtained two great things:

  • Our code will be faster as we don’t have to use reflection anymore.
  • When we compile the code, the compiler will check if our properties (MyTitle in this case) are actually present in our ViewModel. If not, the compiler will inform you of the error and you will be able to quickly fix it.

Performances

I haven’t done any precise test but I’ve actually seen that enabling the Compiled Binding, made my app UI faster and smoother. So they work. Anywaythere are some numbers, According to Microsoft and Xamarin:

  • A  compiled binding with property-change notification is resolved approximately 8 times quicker than a classic binding.
  • A compiled binding without property-change notification is resolved approximately 20 times quicker than a classic binding.
  • Setting the BindingContext on a compiled binding that uses property change notification is approximately 5 times quicker than setting the BindingContext on a classic binding.
  • Setting the BindingContext on a compiled binding that doesn’t use property change notification is approximately 7 times quicker than setting the BindingContext on a classic binding.

Few Tips

  • Always use the Compiled Bindings
  • If possible, set the x:DataType attribute at the same level in the view hierarchy as the BindingContext is set. (When you set the BindingContext, set the x:DataType too)
  • The x:DataType attribute can be re-defined at any point in a view hierarchy. For example you can set the x:DataType at the ContentPage level (like we did before) and then set it again on a label or on a CollectionView (Really you should use them as I wrote here).
  • If for some reason in your view you need to disable the Compiled Bindings, you can set the x:DataType to null, for example:
<StackLayout x:DataType="{x:Null}">
    <Label Text="{Binding MyTitle}" />
</StackLayout>

Conclusion

Compiled Bindings are extremely useful for two main reasons, they are faster and they discover a lot of problems at compile-time. You should really always use them.

As usual, if you like the article or you have questions, leave a comment down here.

Every time we need to present a list of data in our apps, we use a component called ListView. This component does what we want but its performances are very bad, epsecially as it doesn’t support virtualization.

Luckily with Xamarin.Forms 4.3 we can now use a new component called CollectionView. It does exactly the same thing as a ListView but way better and with better performances.

I definitely suggest you to check your projects and replace your ListViews with the new shiny CollectionViews. I’ve done in in all my projects, it doesn’t require a lot of effort and the performances are definitely better. So do it! I’ll now show you how to do it. I’ve create a repository on GitHub with this example. You can find the link at the end of the post.

In the past we had ListViews…

Until version 4.3 to add a ListView we could add a code like this:

<ListView x:Name="MyListView"
           ItemsSource="{Binding MyItems}">
   <ListView.ItemTemplate>
       <DataTemplate>
           <TextCell Text="{Binding Name}" />
       </DataTemplate>
   </ListView.ItemTemplate>
</ListView>

What we have done is to add a ListView to our page called MyListView (naming an object is not mandatory as ideally using correctly MVVM you don’t have to use this name).

Then we have assigned some data to our list using the ItemsSource. MyItems is an ObservableCollection declared into the ViewModel associated.

After we have associated some Data to the ListView we have to show how they should appear. To do this, we can use the ItemTemplate property. There are standard DataTemplate that we can use with ListView and in this case we are going to use TextCell that is just a text. You can see it in the previous XAML code. Of course you can use all the other available DataTemplate or you can create every custom view you want. In the case of the previous XAML, the result is this:

ListView example
ListView example

…now we have CollectionViews

From Xamarin.Forms 4.3 we can now use the CollectionViews.

CollectionView is an improved component that will give you more control and better performances (much better performances).

There are few differences between ListView and CollectionView but most of the times, the transition from ListView to CollectionView is incredibly easy as we can see in the next XAML code. Here we are going to replace the ListView of the previous example with a CollectionView:

<CollectionView x:Name="MyCollectionView"
                ItemsSource="{Binding MyItems}">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Label Text="{Binding Name}" />
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

As you can see there are not many changes. First of all, you have to replace ListView with CollectionView. Same as for the ItemTemplate, replace ListView.ItemTemplate with CollectionView.ItemTemplate.

As you have probably noticed, there is a small difference. For the ListView as DataTemplate we used the TextCell, but this is not available anymore with CollectionViews so we have to write our own view. As we need to show only a text, what we can do is replace the TextCell with a Label.

//From this
<TextCell Text="{Binding Name}" />
//To this
<Label Text="{Binding Name}" />

Now let’s show how the page appears after these small changes:

CollectionView example
CollectionView example

As you can see graphically there are not many differences (but I’d say that the CollectionView appears nicer) but from a performances point of view, the differences are massive,e specially if you are going to add many items to your list.

Conclusion

I really encourage you to replace your ListViews with CollectionViews. It’s probably a matter of minutes but it will improve a lot the performances of your app.

The link for the example showed on this article is:

https://github.com/marcojak/TestCollectionView

As usual if you have any questions, leave a comment and I’ll reply as soon as possible. And if you want more info about CollectionViews and its new features or MVVM (Model-View-ViewModel) let me know and I’ll add some post

Around 10 months ago we hired a contractor to help us with some projects we needed to start. After 9 months his contracts expired but he couldn’t complete the project he was working on, so as the Lead developer in my team, I had to take his code and complete the project. I’ve spent 20 percent of my time completing the project and 80% optimising it. I’ll write several articles on this experience but for now lets’ concentrate on how to improve a C# code using Generics.

At the end of my optimisation with Generics, the code was 20% shorter and around 30% faster.

What are the Generics?

Generics allow you to use a placeholder instead of a type and you can use them with classes , fields, methods, parameters…

For a class a generic could be:

class Node<T>
    {
        private T value;

        public Node(T currentValue)
        {
            value = currentValue;
        }
    }

We have basically created a node that can contain every type we need. This node can contain an int, a string or a class. It doesn’t matter. It works.

We can also create a Generic method like this:

void DoSomeWork(T myParam) { … }

Also in this case we have a method that can accept every type of parameter (an int, a string, a class…).

How Generics can help us?

Going back to my story, what this contractor needed to do is to get the data from an excel file and evaluate that the value contained in each column is valid. To ba valid, a value must be contained in a list of values.

There are around 20 columns we have to evaluate and to do that he wrote this code (I copied only 3 methods but there were 20 of them):

private static bool ValidOverloadWarning(string value, List<OverloadWarning> listOfOverloadWarnings)
        {
            return listOfOverloadWarnings.Select(x => x.Name.ToLower()).Contains(value.ToLower());
        }

        private static bool ValidOverGeoidUnits(string value, List<GeoidUnits> listOfGeoidUnits)
        {
            return listOfGeoidUnits.Select(x => x.Name.ToLower()).Contains(value.ToLower());
        }

        private static bool ValidOverAltitudeUnits(string value, List<GeoidUnits> listOfAltitudeUnits)
        {
            return listOfAltitudeUnits.Select(x => x.Name.ToLower()).Contains(value.ToLower());
        }

The first think you can notice is that the code looks entirely the same, the only difference is the class contained in every list. Moreover I’ve noticed that all these classes have at least 2 fields: Id, Name.

So I thought: “this code can be optimised and this is the perfect situation to use Generics“.

So I started to create a base class with 2 fields: Id and Name.

public class BaseClass
{
    string Id { get; set; }
    string Name { get; set; }
}

After that I changed all the classes like OverloadWarning, GeoidUnits, GeoidUnits,… so that all could inherit from Base Class. For example the class OverloadWarning became:

public partial class OverloadWarning : GenericItem
{
    //...
    // Other properties
    //...
}

After that I was able to replace 20 almost identical methods with a single one, this:

private static T GetItemByName<T>(string value, List<T> list) where T : GenericItem
{
    return list.FirstOrDefault(x => x.Name.ToLower() == value.ToLower());
}

Just doing this I was able to replace 80 lines (4*20) with just 4. A shorter code means that your code is easier to read and maintain and it’s definitely easier to spot any problems or errors and find improvements.

In facts, I noticed that this contractor was doing 2 operations:

  1. check if the value was in the list
  2. if it was present, then he was retrieving this code from the list

It means that you have to search for that element twice and it takes time, so inside the method I wrote, I just replaced the 2 operations with a single one using the command FirstOrDefault that returns the object if it finds it otherwise it returns null. That’s exactly what I wanted to achieve. This is why my method GetItemByName returns a generic type T instead of a boolean value. Replacing two operations with one, helped me to save another 80 lines of code and it allowed me to halve the time to complete these operations

Conclusion

From this short story we have discovered how the Generics can help us. With the use of Generics I was able to replace 160 lines of code with just 4 lines and to replace 2 quite expensive operations with a single one.

Now my code is shorter, cleaner and more important for the client, it takes around 4 seconds instead of 7 to analyse a file.

What do you think about Generics? Do you have more questions or you need help with them? Write here a comment

The MVVM and Fody

The MVVM (Model, View, ViewModel) pattern helps you to organise and structure your code to create better apps.With this pattern you can split your code in 3 main parts:Model: Where you put your dataViewModel: It’s the logic of your app and a link between the Model and the ViewView: It’s the UI of your app (usually written in XAML) The main idea is to keep model, logic and UI completely separated.  And let’s be honest, this is how you should write your app.The interaction between the View and the ViewModel is done with the Data Binding

The Data Binding

The Data Binding is the connection between the UI and ViewModel of your app.You use it to connect a control (eg. a text) of your UI to your logic.Let’s say that we have an Entry (where a user can insert a text) and we want to link it to our ViewModel.We have something like this:in our UI (the View):

<Entry Text="{Binding Username}" Placeholder="Your username" />

In our ViewModel:

//OUR PROPERTY
        private string _username;

        public string Username
        {
            get => _username;
            set
            {
                _username = value;
                OnPropertyChanged();
            }
        }

In this case we have linked the Entry in our UI with the property (Username) in our ViewModel. When the user writes something in this entry, the Username value will change accordingly. And because the link is bidirectional (by default but you can change this behaviour), if we change the property value (eg. loading it from a database) the UI will change accordingly. It’s amazing. Isn’t it?

How to improve the code

To make a link between the UI and the ViewModel we need to use properties. Inside the set of each property we must call OnPropertyChanged (so our ViewModel must implement the INotifyPropertyChanged interface).It works, that’s great, but in a View usually we have a lot of interactive controls and for each of these we should need a property so there are cases where in our ViewModel we have many properties and you can imagine that the code is not readable anymore.Can we improve this? YES!

FODY

Fody is a library for IL weaving (the process to manipulate/inject code in IL). To put it easy, Fody will update automatically our code for us adding new cool features. In this case we are interested in a particular nuget plugin for Fody called PropertyChanged. This plugin will “Inject code which raises the PropertyChanged event, into property setters of classes which implement INotifyPropertyChanged.”What it means, is that we don’t have to explicitly call OnPropertyChanged() but we can instead use Auto-Properties.We can therefore convert our previous Username property to this:

public string Username { get; set; }

We have reduced the number of lines of code from 10 to 1. IMPRESSIVE!. Let’s say that in our ViewModel we have 20 properties, we have 200 lines of code only to declare our properties. With Fody & PropertyChanged plugin we can have only 20 lines of code instead of 200, saving 180 lines! Not Bad!

How to add it to your project

The process in incredibly easy:

  1. In your project install the Fody plugin (only in your PCL/.Net Standard project, in case of Xamarin, you don’t need to install in the Android, iOS,UWP projects): Fody
  2. Install the PropertyChanged plugin (only in your PCL/.Net Standard project): PropertyChanged
  3. Add to your PCL/.NetStandard project a new file called FodyWeavers.xml
  4. Open the file and change its content to:
<?xml version="1.0" encoding="utf-8" ?>
<Weavers>
    <PropertyChanged/>
</Weavers>

IMPORTANT: PropertyChanged will convert your properties only inside the viewmodels that implement the INotifyPropertyChanged interface. So don’t forget to do it in your ViewModels where you want to use Fody PropertyChanged:

public class LoginViewModel : INotifyPropertyChanged

Usually a desktop platform has a lot of available resources so many developers tend to avoid to improve the quality of their code.On a mobile platform the resources are quite limited and improving the code could make a huge difference. It can transform a slow and annoying app in a great fast and great one.Today, using the code I’ve written for one of my app Tv Series Time Manager, we are going to see how improving the code can make a huge difference in the loading time of your apps.

LINQ
LINQ

Improve your code – LINQ is your friend

Tv Series time manager allows you to keep track of your preferred tv series.It uses a public API to get information about all the TV Series created. As you can imagine there are thousands and thousands of Tv Series so we need to handle lists of thousands of items.Every time we launch the app, it searches online updated about the Tv Series you are following (new episodes, release dates, and so on). This can be a quite intensive task as the API we need to call returns a JSON file with more than 34000 items.The first time I’ve written the updated method I had this code:

var localTvShows = LocalData.GetAllTvShows(); 
var remoteUpdatedTime = await WsData.GetUpdatedShows(); 
foreach (var info in remoteUpdatedTime) 
{ 
    var show = localTvShows.FirstOrDefault(x => x.id == info.Key); 
    if (show != null && info.Value > show.updated) 
    { 
        updateRequired = true; 
        break; 
    } 
}

            if (UpdateRequired)
            {
                foreach (var info in remoteUpdatedTime)
                {
                    var show = localTvShows.FirstOrDefault(x => x.id == info.Key);
                    if (show != null && info.Value > show.updated)
                    {
                        var remoteserie = await WsData.GetShow(show.id);
                        SqlHelper.SyncSerie(show, remoteserie);
                        var episodeList = await WsData.GetEpisodes(show.id);
                        SqlHelper.SyncEpisodes(show.idLocal, episodeList);
                    }
                }
            }

I load the local Tv Show followed by the user and the remote Tv Series with the corresponding update time.Inside the first foreach I check if I need to update the local Tv Series.In case I have to update a Tv Series, I use a second foreach to update every local TV Series inside the local Sql database. (To add SQLite database to your app, you can read this tutorial)The code worked pretty well but I wasn’t satisfied by the loading time so I started to look for a way to improve the performances and here I discovered once more that LINQ is our friend.

The new code with LINQ

I decided to use LINQ to evaluate if I have to update a tv series, so I’ve written the code replacing the old one with this:

var seriesToUpdate = from remoteTime in remoteUpdatedTime
                join localShow in localTvShows 
                    on remoteTime.Key equals localShow.id
                where remoteTime.Key == localShow.id && remoteTime.Value > localShow.updated
                select localShow;

            if (seriesToUpdate.Any())
            {
                foreach (var show in seriesToUpdate)
                {
                    var remoteserie = await WsData.GetShow(show.id);
                    SqlHelper.SyncSerie(show, remoteserie);
                    var episodeList = await WsData.GetEpisodes(show.id);
                    SqlHelper.SyncEpisodes(show.idLocal, episodeList);
                }
            }

Speed Test

Now it’s time to see if the new code is really better than the first (Obviously it is 🙂 ). To do so, I’ve divided the code in two parts.

  • Evaluate if an update is required (Part A)
  • Update the Tv Series (Part B).

To give you the idea of how much time we can save, I’ve enclosed both the code in a for statement repeating the it for 100 times. These are the result:

Part A

  • OLD CODE:  Elapsed Time: 1077 ms
  • NEW CODE: Elapsed Time:   225 ms

Part B

  • OLD CODE:  Elapsed Time:  590 ms
  • NEW CODE: Elapsed Time:   122 ms

Total

  • OLD CODE:  Elapsed Time:  1667 ms
  • NEW CODE: Elapsed Time:    347 ms

Looking at the time spent by the old and new code we  went from 1667 ms to 347 ms, saving 1320 ms. The difference is HUGE.From the point of view of a user, saving almost 1.5 seconds makes a massive difference, maybe the difference between keeping your app or uninstalling it.

Conclusion

A mobile device has a limited amount of resources and users don’t like to spend time waiting in front of a loading screen. Even the most useful app, if not optimized will be uninstalled by the users. This is why it’s really important to optimize your code.Today we have seen that with a good use LINQ  we can massively reduce the time used by our code.If you like the article, comment and share it!

%d bloggers like this: