Archive

Posts Tagged ‘C#’

Using yield statements for statistical calculations.

June 29th, 2009

Reading time: 4 - 6 minutes

Enumerations and the yield statement in C# are a pretty powerful weapon in every developers’ arsenal. In this post I am going to show how we can use enumerations as co-routines to perform sequential infinite calculations. I will also show what’s the performance price to pay for the syntactic sugar involved in the process.

The idea is not to improve upon known patterns, but to show a different scenario where enumerations can provide us with an elegant solution, albeit not always the most efficient one.

For the example we will use a ported code to calculate normally distributed random numbers. The original C++ code can be found here: http://www.agner.org/random/

We started by creating 3 different versions of the code. The first is an straight forward C++ style version that looks like this:

First we initialize the required prerequisites, the uniform random number generator. To be fair in the performance comparison all versions use the same Uniform Random Generator.

4 

3

The next version returns an enumerator that allows us to iterate 100000 times that looks like this:

3.yield.statement

The last one allows us to inject though a lambda expression the random generator that intend to use. That version has a very interesting side effect, you are allowed to use whatever random generator that you choose.

6

As we can see here, the generator lambda is quite simple, it just gets uniformly distributed random values and makes sure they get normally distributed.

7

The interesting property is that the execution works like a coroutine, returning the value but continuing at the last position after the return yield when it is called the next time. The side effect is that the smaller the procedure the higher the overhead ratio. For example, in this case, we choose to inject the uniform random generator call, that is called waaay too much in an small timeframe causing an small overhead to add up a lot.

This is a comparative study of the execution time of each one of the methods, where the injecting lambda taking as much as 50% more than the plain vanilla version. These performance measures would at first sight negate the idea of using yield statement; however, the good news is that this is an extreme case. This is what it is called a tight loop, where even a method call can do quite a difference.

1

That is shown best in the difference between the TestNormalWithLambda and the TestNormalEmbeeded, where the Random generator is passed as a parameter. In that case there is only a 20% increase, pretty big for a tightly packed loop, but not too much if you have an standard use.

As a conclusion, use iterators with yield statements where you have iterative methods and are not supposed to be used in tight loops; as the readability they provide is far greater. You have lots of time to obscure your code optimizing for performance after you know your algorithm works as expected. As Knuth said: “We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil”.

  • Share/Bookmark

Technology ,

Refactoring Friendly INotifyPropertyChanged Properties

May 18th, 2009

Reading time: 9 - 15 minutes

If you have been working on Windows Presentation Foundation or Silverlight 2.0/3.0 you may already be aware of a pretty interesting design pattern called MVVM (Model-View-ViewModel).

MVVM relies on the quite simple but important interface INotifyPropertyChanged in the System.ComponentModel namespace. Its role in MVVM is to allow you to notify when changes have occurred in your ViewModel so that your UI is able to respond to those changes.

// Summary:
//     Notifies clients that a property value has changed.
public interface INotifyPropertyChanged
{
   
// Summary:
    //     Occurs when a property value changes.
    event PropertyChangedEventHandler PropertyChanged;
}

 

As you can see the interface is quite simple, it just ask us to implement the property changed event. The usual way to use it is the following:

private int myIntProperty;

public int MyIntProperty
{
   
get { return myIntProperty; }
   
set
   
{
       
if (myIntProperty != value)
       
{
           
myIntProperty = value;
           
OnPropertyChanged(“MyIntProperty”);
       
}
   
}
} 

 

The “MyIntProperty” string is used to signal that the property that has changed is MyIntProperty so that our bindings gets notified of the value changed.

This approach has a slight problem, this string is not very refactoring friendly because it is binded to the property name, but it is not a “compiler verifiable entity”. In the case of the property it may look simple, just going ahead and change it. But, what happens when we are actually handling that property somewhere? Again we have to know that changing it will cause changes everywhere in our code base when that property change is handled.

If we do automatic refactoring, some tools may be able to know that they should change the property name too when refactoring and all strings. But that is a long shot if you have different classes with similar named properties, because the rename may change some strings that shouldn’t be renamed on the first place. Luckily there are workarounds to this problem.

What we would like to do is have something similar to this:

private int myIntProperty;

public int MyIntProperty
{
   
get { return myIntProperty; }
   
set
   
{
       
if (myIntProperty != value)
       
{
           
myIntProperty = value;
           
OnPropertyChanged(MyIntProperty);
       
}
   
}
} 

 

The current version of the C# language do not support passing Properties as a delegate so we cannot create a runtime entity that may allow us to find out in the OnPropertyChanged event handler who is calling.

But we do have something that behaves in a similar fashion, we have Lambda Expressions and Expression Trees. So what if we can do the following?

private int myIntProperty;

public int MyIntProperty
{
   
get { return myIntProperty; }
   
set
   
{
       
if (myIntProperty != value)
       
{
           
myIntProperty = value;
           
OnPropertyChanged(() => MyIntProperty);
       
}
   
}
}

 

It turns out that this may work, as the compiler is creating an expression tree out of that delegate, so we may be able to extract the property name out of it.

public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
   
MemberExpression body = (MemberExpression)expression.Body;
   
return body.Member.Name;
}

 

After we solved that we are able to implement our PropertyChanged handler pretty easily like this:

/// <summary>
/// Raises this object’s PropertyChanged event.
/// </summary>
protected virtual void OnPropertyChanged(string propertyName)
{
   
this.VerifyPropertyName(propertyName);    if (this.PropertyChanged != null)
       
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}       

 

protected void OnPropertyChanged<X>(Expression<Func<X>> expression)
{
   
string propertyName = GetPropertyName(expression);
   
OnPropertyChanged(propertyName);
}

Now the only thing that we require is to implement a base class for our ViewModel and some helper class to encapsulate the GetPropertyName functionality and we are ready to have refactoring friendly INotifyPropertyChanged properties.

You can also download a complete implementation from here and 2 visual studio snippets, one for ViewModel classes that implement the INotifyPropertyChanged interface and another one for properties that notify they had been changed. 

You can get it from: http://www.corvalius.com/blog/?attachment_id=26

  • Share/Bookmark

Technology , ,