Wednesday, June 10, 2009

What a wonderful world

Recently I read a lot about the M-V-VM pattern and I wanted to try it out. So I started small with a WPF-application implementing a listview showing some events related to sleep medicine. I’ve created a simple model with a collection of various data. This model is the data-provider for a ViewModel which is databind to this view:



So far, so good; worked pretty easy. I then read something about the graphical ability of WPF, which should be very bad in displaying a lot of graphical objects. Again, I wrote a sleep-medical-application, but this time showing some random biosignals with events:



The problem here was the very long signal build of thousands of Polyline-segments. And indeed, this brought WPF to its knees. You can’t show some signals with the pure use of WPF-technology. I instead used GDI+ inside of a Canvas-element for the signal and the VirtualCanvas-technique for the events (read here about it). With that I managed to preserve databinding on the modifiable objects (the events): you can move them around and change their duration by dragging their border.

In a second step, I combined the model of the ListView with that of the biosignals and injected it into its ViewModel. Of course, every ViewModel is being unittested – what a wonderful world:


Thursday, June 4, 2009

C#-For and VB.NET-For

Yesterday I wondered why on earth my simple VB.NET-For-loop produced an error:

Dim collection As New List(Of Integer)
collection.Add(1)
collection.Add(2)
collection.Add(3)
collection.Add(4)
collection.Add(5)

For i As Integer = 0 To collection.Count - 1
Console.WriteLine(collection(i))

If collection(i) = 2 Then
collection.RemoveAt(i)
End If
Next

I’m coming from a Java / C#-background, so I tried the same loop in C#:

var collection = new List<int>();
collection.Add(1);
collection.Add(2);
collection.Add(3);
collection.Add(4);
collection.Add(5);

for (int i = 0; i < collection.Count; i++) {
Console.WriteLine(collection[i]);

if (collection[i] == 2) {
collection.RemoveAt(i);
}
}

Et voilá, the result is what I wanted. So I made my discovery of the day: C#-For isn’t VB.NET-For.

In the cold light of day and using the debugger, it seems obvious that the VB.NET-For doesn’t check the condition on every iteration. It just duplicates the loop as often as it is stated in the For-statement.

The C#-construct is smarter as it checks in every iteration if the condition is true. But if it’s true that this is the difference between the two Fors, then the C#-loop must be slower. So, let’s check it out:

Dim start = DateTime.Now

For i As Integer = 0 To 1000000000
' nothing
Next

Console.WriteLine(Now.Subtract(start).ToString())

Vs.

var start = DateTime.Now;

for (int i = 0; i < 1000000000; i++) {
// nothing
}

Console.WriteLine(DateTime.Now.Subtract(start).ToString());

And indeed, the VB.NET-For-loop wins on my system with 3.734s to 4.687s!