[Best Practice #2] Specify length of collections when you know it.

In the past of programming, developers were fighting for every single byte of memory and every single computing cycle. But with advancement of computers, with memory getting more and more cheaper, with programming languages getting more user friendly and offering compiler sugar, developers got lazier. But this is a good thing. Software gets insanely complex, which requires powerful computers and high level programming languages, that provide many things out-of-the-box.

Unfortunately times change. Today we live in the cloud. We need to design our software so it can withstand massive loads of traffic and parallel execution. This paradigm kinda brings back the old days. It starts to really matter what we do under the hood. Each line is again important. Each object reference is crucial.

In that direction, today I want to talk about the useful collection classes like List<T> and Queue<T> that the .NET Framework provides for us. Out of the box many times developers overuse those classes without thinking of the consequences. One particular feature I want to stress in this article is the two different constructors that those classes have. I will focus on List<T>.

The class has three constructors, but I will talk about two of them.

Do you remember the time before List<T> was available? How do we represent collections of the same item in programming? We use arrays, of course. And there comes this magical class that gives us a collection that you can easily Add and Remove items to. Because as you know, arrays, once declared, have a fixed number of elements. If you wanted to add elements to the collection, you needed to create a new array with bigger capacity and copy all of the old elements to the new array.

Well, as it comes to no surprise, this is exactly what List<T> is doing. A quick look at the class source code, we can see  that there is a private member:

private T[] _items;

So what happens when we create a List<T> with no capacity? An empty array is being created and from that point, every time we add an element, the code sets new capacity to the array by creating a bigger one and coping the elements to the new one.

On the other hand if we set the capacity beforehand in the constructor, then all of the adding of elements just populates elements of the already allocated array.

You can imagine how this can impact performance and memory consumption.

To demonstrate the difference I have created a small test using the awesome BenchmarkDotNet library.

using System;
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Running;

namespace Blog.BestPractices
{
    class Program
    {
		static void Main(string[] args)
        {
            var summary = BenchmarkRunner.Run<TestLists>();

            Console.ReadLine();
        }
    }

    [MemoryDiagnoser]
    public class TestLists
    {
        private const int _iterations = 1000000;

		[Benchmark]
        public void TestNormalList()
        {
            var list = new List<byte>();
            for (var i = 0; i < _iterations; i++)
            {
                list.Add(123);
            }
        }

        [Benchmark]
        public void TestScopedList()
        {
            var listWithLength = new List<byte>(_iterations);
           
            for (var i = 0; i < _iterations; i++)
            {
                listWithLength.Add(123);
            }
        }
    }
}

And here are the results of that benchmark:

// * Summary *

BenchmarkDotNet=v0.10.9, OS=Mac OS X 10.12
Processor=Intel Core i5-4250U CPU 1.30GHz (Haswell), ProcessorCount=4
.NET Core SDK=1.0.4
  [Host]     : .NET Core 1.1.2 (Framework 4.6.25211.01), 64bit RyuJIT
  DefaultJob : .NET Core 1.1.2 (Framework 4.6.25211.01), 64bit RyuJIT


         Method |     Mean |     Error |    StdDev |    Gen 0 |    Gen 1 |    Gen 2 |  Allocated |
--------------- |---------:|----------:|----------:|---------:|---------:|---------:|-----------:|
 TestNormalList | 6.349 ms | 0.0941 ms | 0.0880 ms | 492.1875 | 492.1875 | 492.1875 | 2048.48 KB |
 TestScopedList | 5.279 ms | 0.0636 ms | 0.0595 ms | 242.1875 | 242.1875 | 242.1875 |  976.63 KB |

You can see that using the list with fixed capacity allocated two times less memory and has better performance.

In conclusion I want to say, that I am perfectly aware that this example does not fit everywhere, because sometimes you just don’t know how much elements you would need. And the is totally fine. What I am saying is that you should always keep in mind the numbers above and when you instanciate a list, ask yourself if you cannot determine its size.

[Best Practice #1] Override the ToString() method of your classes

This is first of series of best practices and tips I have for my fellow software developers. The articles are not ordered by importance, they are completely random. (And I mean real random, not computer random)

There are a few methods available for you from the object class in .NET, which provide some basic functionalities for you structures. There’s a bunch of them, but giving definition and explanation for each one is not a target of our article. The one I am going to point out here is

public virtual string ToString()

Why this is important?

Well it is definitely not “a must”, but I have found it to be dramatically helpful during debugging. Let me show you why.

Imagine this simple class:

	public class Person
	{
		public Person(int id, string firstName, string lastName)
		{
			Id = id;
			FirstName = firstName;
			LastName = lastName;
		}

		public int Id { get; }
		public string FirstName { get; }
		public string LastName { get; }
	}

Now if I am doing some application, which populates a list of type List<Person>, by loading it from a database and I need to debug it, this is how my QuickWatch would look like:

As you can see, if I want to see the details of each object, in order to determine if some Person is there, I need to expand them one by one. Here I have only 5, but having a collection of thousands of items is not something unusual.

The trick that comes in handy is the previously mentioned ToString() method of the object base class. That method is there for a good reason. Whenever the .NET framework needs to convert some object into a textual representation, this is when that method is invoked. Also this method is used by tools like Visual Studio, to populate simple textbox based controls as the Value column we see in the screenshot.

Now let’s override our method in the Person class and then take a look at the QuickWatch. Here is our implementation:

	public override string ToString()
		{
			return $"[{Id}] {FirstName} {LastName}";
		}

As you can see, we are just returning somewhat meaningful string in that method. We are doing this by using string interpolation. By doing this, here is our new screenshot:

Here you can see, that our Value column looks much better now. I can see the text interpretation of our class here and not having to expand the objects in order to know, which object is the one with Id = 3.

Another place, where ToString() is used is in the string interpolation. Whenever you put an instance of an object in the curly brackets, the .NET is using the ToString() method in order to fill that. So if we have the following code:

Console.WriteLine($"The first person in the list is: {list[0]}");

This is the difference we have:

You see, if you don’t have a ToString() method overridden, this means that the default one will be used, that is implemented in the object class. And that one returns a string with the full class name.

With everything said, I want to show you how helpful that practice can be in your daily developer’s life. Debugging and writing things in the console is usually big part of what every developer does on a daily basis. Simply overriding the ToString() method can save you a lot of time and energy, and usually it is one line of code.

 

Programming Best Practices

In this series I will write some best practices that I have adopted and validated to be very useful, even critical sometimes, in my everyday’s life as a C# developer.

The guidelines I am talking about don’t necessarily apply only to C#, but this is the language I have most experience with.

I will start posting such an article every few days. And I will be more than happy to read your comments and suggestions about something I have missed or express your opinions against the ones I have put up here.

Of course I don’t consider my suggestions to be a silver bullet in programming, but I am applying those standards strictly and I do believe they are valid and work.

Below you will find list of articles with links, which I will update when a new article is published.

Best Practice #1: Override the ToString() method of your classes
Best Practice #2: Specify length of collections when you know it

Silverlight ResourceDictionary Issues

I have been developing WPF/Silverlight Applications about half an year already and I am charmed by the power of those technologies. But still there are some very strange and annoying issues I came upon, especially in my Silverlight implementations. The most favourite one is the one I will be explaining in this post. I am talking about the ResourceDictionary class.

Little intro

ResourceDictionary is a major class in the Silverlight platform, used to hold all the needed resources that you might create and use during your application lifecycle. This includes Custom Templates, Styles, Brushes, Images and many other very cool and useful stuff. This class is used by the runtime in order to choose and apply all these nice peaces you have put in. This brings to mind that this is one of the fundamental classes of the framework and therefore it is very well structured.

The dissapointment

This is where it gets messy. Having in mind that this is a ResourceDictionary you might think that it has all the great features that the standart Dictionary class reveals. Since it is being derived from IEnumerable interface, you might think that you can easily “foreach” that Dictionary and circle aroud your resources. Well you thought wrong ! This is how the GetEnumerator method used by the “foreach” looks like:

IEnumerable<...>.GetEnumerator()
{
throw new NotImplementedException();
}

So if you try to run this very simple code:

ControlTemplate tmp;
ResourceDictionary dict = new ResourceDictionary();
dict.Add("template1", new ControlTemplate());
dict.Add("template2", new Style());

foreach (object obj in dict)
{
if (obj is ControlTemplate)
tmp = obj as ControlTemplate;
}

you will get this nice thingy here:

NotImplementedException

The sad thing is that this was a behaviour in Silverlight 2 Final release and it is still present in Silverlight 3 Beta. I really hope this will be exposed in the Final release of Silverlight, because personally in my opinion this is quite useful in some complicated scenarios.

MergedDictionaries

This was a problem not being solved in Silverlight 2, but in the 3rd version it has been resolved, so I am not going to brag about it. Still I have been experiencing some difficulties in using them in the generic.xaml, but I am planning to write a separate article on that topic.

The conclusion

I want to say that this article of mine is not intended to mess around with the Silverlight guys from Microsoft. Silverlight is a great technology and I absolutely love it. I have been developing Silverlight applications for almost an year now and I tend to use it in every project I am involved in. I am pointing out those issues just to help the other Silverlight developers, who stumble upon those problems and can’t figure out why. I have spent days trying to fix some of the issues I am writing about and most of the time I spent on figuring out why it is happening. The more developers I can help by sharing my experience the better !

Silverlight Tip: Why do I get “An unhandled exception of type ‘System.OutOfMemoryException’ occurred in Unknown Module.” ?

In the past 4-5 days I have been busy, trying to figure out a VERY strange problem with a PropertyGrid solution we have done in Silverlight. Let me first explain quickly what is the solution about.

This is a PropertyPanel Silverlight control, used to expose the public properties of a bussiness object and allow the user to change them back to the object. Needless to say, the control had to populate these properties via reflection by itself. The tricky part is that we needed to create custom editor controls for each property type.

To make this flexible we added all the property editors as a simple ContentControl and dynamically changed the ControlTemplate of the editor, based on the type of the property.

So far so good. We have implemented the whole mechanism for populating the properties, dynamically creating the ContentControl editors and choosing the ControlTemplate from a list of templates, being predefined.

We have added all those things in a Silverlight Library solution and created another solution (a Silverlight Application, what else ?), where we made a test by passing a custom business object to the control and show it.

Everything went well when we used only the generic build-in controls from the Silverlight SDK for the editors. As soon as I have added a controls from a 3rd Party, or even from System.Windows.Controls, I got the strangest exception on loading:

“An unhandled exception of type ‘System.OutOfMemoryException’ occurred in Unknown Module.”

This was just not enough information. No stack trace, no InnerException, nothing ! I started debugging and pulling out things one by one from the functionality to get to the bottom of the problem. Nothing helped. I spent more than 4 days trying to solve it, but I couldn’t. Finally, while browsing the Google results for the message of the exception, I got to this address: http://slpropertygrid.codeplex.com/

This is a similar solution by some guys, who faced the same problem. What I have noticed is that they had the problem when the referencing DLLs were broken. As I took a look at our solution I found out that we haven’t referenced the 3rd Party DLLs in the sample solution at all ! I have only referenced them in the Library solution. One might think that this is a normal thing to do, because these DLLs should be exposed to the simple solution by the Library one. Well, one is wrong ! Turned out that Silverlight has some issues on that topic. The exception is totally misleading and if I haven’t found that solution, I wouldn’t had had solved the problem.

Blogging from MS Days 09

Here I am at Microsoft Days 2009 Conference.

It is already the end of the second day and I am waiting to hear my last session for this year’s MS Days.

My overall satisfaction with the conference is not really as I expected. The location is moved, which in my opinion, is a bad thing. So far the conference was being held in the IEC (International Exhibition Center – [Google Maps]) just at the end of Sofia. Getting there with a car is fairly easy and there is a direct bus transport, stopping at the main entrance of the Center.

This year’s conference is being held in Hotel Kempinski ([Google Maps]), which is in the town’s center. You can imagine that getting there is a nightmare, getting out of there is a nightmare and parking is a new level of nightmare. I must agree that some of the halls are bigger than the one at the IEC, but this is not really the issue the organisation guys are facing.

As it is expected I came here to hear as more Silverlight and WPF sessions as I could. So far I attended three sessions of this kind. Some were good, some were bad. Honestly I expected a storm of Silverlight 3 sessions since it is brand new and being announced about 3-4 weeks ago. Unfortunately there was only one that was regarding Silverlight 3. This is kinda dissapointing.

Another interesting session I saw was “Windows 7 – Deep Dive”. Quite an interesting one, it really got me in to wanting to install that new system. So as soon as I have the chance, I will install it and give it a go.

There was a showroom at the conference where you could check out Microsoft Surface and play around with it. Quite a cool gadget. I hope that I will have the chance to work on such a technology some day.

As a conclusion I can say that Microsoft Days 2009 was nice, but I was expecting much, much more. But this won’t stop me from attending MS Days 2010. I hope it will beat the crap out of this one !

Visual Studio on Windows Mobile

Today, while I was circling around my favourite “morning coffee” RSS feeds, I stumbled upon some of the PDC sessions on Silverlight that were held in the past few days, and I was just stunned by the very interesting session Microsoft Silverlight 2 for Mobile: Developing for Mobile Devices. I was just so fascinated by the session that I literally started laughing and everybody in the office just gazed at me in misunderstanding.

In the session you can see how Visual Studio can be run on Windows Mobile device. Yes it is pretty hard to write code and interact with the environment from the little screen of the mobile device, but still it is very very interesting !

This is not the first session from PDC, that I have watched. In the next days I will post more links and articles about the ones I have seen and what is interesting about them. Also I plan to post some articles about a few problems I stumbled upon my development in the last few month, so stay tuned !