Archive

Posts Tagged ‘fasterflect’

Revisit Dynamic Event Handler in .NET

July 11th, 2012 Comments off

A while ago I blogged about how to build a catch-all handler for .NET events and delegates. That solution uses LCG to generate CIL for the dynamic delegate. The latest version of Fasterflect however uses Expression Trees to generate the dynamic delegate. So I thought I would post the new solution here for completeness.

Fasterflect 2.0 Release

March 21st, 2010 5 comments

I am pleased to announce the release of Fasterflect 2.0. For those who are not aware of Fasterflect, it is a library that helps you get rid of the complexity and slow performance of .NET Reflection. Check out this Code Project article and a previous announcement for an introduction.

Fasterflect 2.0 comes with a great number of additions & changes, which are possible thanks to the fact that I am no longer the only developer of this project; instead, Morten Mertner (author of Gentle.NET) has joined me since the beginning of 2.0 and made huge contribution ever since. Let’s look at some highlights of this release.

The most exciting addition in this release is that Fasterflect now includes a Query API. Previously you can only use Fasterflect to construct objects or performs invocations (these 2 usages are now referred as Access API). With this release, you can query .NET reflection metadata with Fasterflect although much simpler than what you have to do with the built-in .NET reflection. You can even do more thing with this Query API than you can with .NET reflection out of the box. For example, you can choose to exclude backing members from a lookup or enable partial-name lookup. All you need to do in order to have these level of control is specifying a proper Fasterflect binding flag. The nice thing about Fasterflect binding flag is that it is also fully supported in the Access API.

Next, the Access API is now fully integrated with .NET reflection metadata classes, such as ConstructorInfo, MethodInfo, FieldInfo etc. This integration makes it able for you to mix & match the usages of Query API and Access API as well as allows you to use .NET reflection as it is while delegating the invocation to the fast CIL-generation engine of Fasterflect.

We have also built on top of the core Fasterflect engine some add-on services such as advanced object construction, deep cloning and object mapping. We expect to have more of these services in future releases and of course, you can send us your contributions too.

Users of previous versions of Fasterflect should be aware of the following breaking changes.

  • Many existing extension methods have their names changed as we went through the process of improving API’s consistency & usability. We hope these changes are for the better because now we have 2 developers vote on the conventions instead of 1 like previously :-) . You would have to make some code change when switching from 1.1 to 2.0, but the changes should be very straight-forward in most cases except for the other changes described below.
  • Fasterflect extension methods now don’t require a type parameter, which we have found to be inconvenient because people are forced to append <object> to the call even when they don’t care about the return value or its type. These methods now simply return result of type System.Object and you can cast to the correct type if you need to.
  • Batch fields/properties setting are gone. They are replaced by the object mapping add-on service which is more flexible, sophisticated and faster (CIL code generation is used behind the scene). Batch setting of static members is not supposed though because we think it’s not a common scenario. That said, do let us know if you have this need and we will add support for it in the next minor release.
  • The class Reflector and its methods are now gone. We instead employ a custom-built weak reference-based cache to assure that generated CIL can be garbage-collected when memory is low.

Last but not least, the project wiki on CodePlex is fully populated with comprehensive documentation. While Fasterflect is still ridiculously easy to use, it now has a much bigger API and is more sophisticated than it used to be (e.g. with Fasterflect binding flags). Therefore, documentation should be of great help for those who want to understand everything about Fasterflect to use it effectively in even advanced scenarios without having to dig through the source code.

You can download the binary, source code and CHM API help file in the Fasterflect 2.0 release page in CodePlex. If you want to explore Fasterflect in details, surf through the project wiki. If you just want to jump right into the usages without any further introduction, check out the 2-minute-guide to Access API and this page about the Query API. Finally, the comprehensive unit test suite included in the code download can also serve as good reference for the API.

Fasterflect vs. C# 4.0 Dynamic

December 31st, 2009 4 comments

As .NET 4.0 final release will hit the market pretty soon, it’s worth discussing the value of Fasterflect in the face of C# 4.0′s dynamic keyword.  (If you aren’t familiar with C# 4.0 dynamic, you should read my article on C# 4.0 before continuing.)

To recall, Fasterflect was designed to address 2 key disadvantages of .NET Reflection: ease of use and performance.  As seen in my article about C# 4.0, the dynamic keyword nicely addresses the easy of use with a resulting syntax looking even nicer than Fasterflect.  How about performance?

I improved the benchmark application of Fasterflect to add some benchmark code comparing between the performance of C# 4.0 dynamic and Fasterflect.  Here is result of method invocation benchmark.

fasterflectbenchmark

While performing slower than Fasterflect’s cached API, C# dynamic performs much better than Fasterflect’s standard API.  (Not surprisingly, the C# dynamic binding doesn’t resort to the slow reflection mechanism internally.)

With this awareness in mind, together with the understanding about the features of C# dynamic and Fasterflect, let’s discuss about areas where Fasterflect shines even in the face of C# 4.0 dynamic:

  • C# dynamic doesn’t handle invocations performed based on dynamic information (i.e. field name read from XML file).
  • C# dynamic does handle certain types of dynamic invocations, including static method invocation, static property invocation and constructor invocation.
  • C# dynamic doesn’t handle non-public members.  So you’ll receive exception if trying to, say, invoke a private method.
  • When performance is more critical than readability then the Fasterflect’s cached API might be favored over C# dynamic.

Granted, there should be workarounds for the first 3 items.  For example, if you want to invoke static method dynamically with C# dynamic, you would have to workaround like the approach described in this article.  However, the approach uses reflection behind the scene so you would have the same performance issue to start with.

This doesn’t say that Fasterflect is better than C# dynamic though.  While both share a couple of features and maybe used interchangeably in some scenarios, they also have different problems of their own to address.  There are many things that you can do with C# dynamic that you couldn’t do with Fasterflect, e.g. implementing an interceptor to dynamically handle all method invocations (or missing methods) etc.  So, pick the right tool for your problem at hand.

Categories: .NET Tags: , , ,

Speaking at Barcamp Saigon 2009

December 16th, 2009 4 comments

I spoke at Barcamp Saigon 2009 last Sunday. It was a fun event. Met a number of interesting people and learned some new things from other sessions. I talked about the two open-source libraries I developed, Fasterflect & Combres. Below are the slides I used for my presentations.

.NET Reflection Made Fast & Simple – Fasterflect 1.1 Release

November 19th, 2009 7 comments

I’m pleased to announce that version 1.1 of Fasterflect, the fast & simple .NET reflection invocation library, is already released in CodePlex. The download include Fasterflect binary, code documentation, benchmark application source, sample code, unit test source (95%+ coverage, can be used to learn about all usage aspect of Fasterflect).

For an introduction to Fasterflect, including its design, APIs, and benchmark, please refer to this Code Project article.

Changes since version 1.0 beta (the one documented in the Code Project article) include:

  • Support array types (construction, set element, get element)
  • Support structs
  • Support ref/out parameters
  • Support lookup by covariant parameter type
  • Inference of parameter types for non-null arguments
  • Several bug fixes

Sample Code

class PersonClass
{
    private int id;
    private int milesTraveled;
    public int Id
    {
        get { return id; }
        set { id = value; }
    }
    public string Name { get; private set; }
    private static int InstanceCount;

    public PersonClass() : this(0) {}

    public PersonClass(int id) : this(id, string.Empty) { }

    public PersonClass(int id, string name)
    {
        Id = id;
        Name = name;
        InstanceCount++;
    }

    public char this[int index]
    {
        get { return Name[index]; }
    }

    private void Walk(int miles) 
    {
        milesTraveled += miles;
    }

    private static void IncreaseInstanceCount()
    {
        InstanceCount++;
    }

    private static int GetInstanceCount()
    {
        return InstanceCount;
    }
    
    public static void Swap(ref int i, ref int j)
    {
        int tmp = i;
        i = j;
        j = tmp;
    }
}
struct PersonStruct
{
    private int id;
    private int milesTraveled;
    public int Id
    {
        get { return id; }
        set { id = value; }
    }
    public string Name { get; private set; }
    private static int InstanceCount;

    public PersonStruct(int id) : this(id, string.Empty) { }

    public PersonStruct(int id, string name) : this()
    {
        Id = id;
        Name = name;
        InstanceCount++;
    }

    public char this[int index]
    {
        get { return Name[index]; }
    }

    private void Walk(int miles) 
    {
        milesTraveled += miles;
    }

    private static void IncreaseInstanceCount()
    {
        InstanceCount++;
    }

    private static int GetInstanceCount()
    {
        return InstanceCount;
    }
    
    public static void Swap(ref int i, ref int j)
    {
        int tmp = i;
        i = j;
        j = tmp;
    }
}
class Program
{
    static void Main()
    {
        // Load a type reflectively, just to look like real-life scenario
        var types = new[]
                        {
                            Assembly.GetExecutingAssembly().GetType("FasterflectSample.PersonClass"),
                            Assembly.GetExecutingAssembly().GetType("FasterflectSample.PersonStruct")
                        };
        Array.ForEach(types, type =>
                                 {
                                     ExecuteNormalApi(type);
                                     ExecuteCacheApi(type);
                                 });
    }

    private static void ExecuteNormalApi(Type type)
    {
        bool isStruct = type.IsValueType;

        // Person.InstanceCount should be 0 since no instance is created yet
        AssertTrue(type.GetField<int>("InstanceCount") == 0);
        
        // Invokes the no-arg constructor
        object obj = type.Construct();

        // Double-check if the constructor is invoked successfully or not
        AssertTrue(null != obj);

        // struct's no-arg constructor cannot be overriden, thus the following checking
        // is not applicable to struct type
        if (!isStruct)
        {
            // Now, Person.InstanceCount should be 1
            AssertTrue(1 == type.GetField<int>("InstanceCount"));

            // What if we don't know the type of InstanceCount?  
            // Just specify object as the type parameter
            AssertTrue(type.GetField<object>("InstanceCount") != null);
        }

        // We can bypass the constructor to change the value of Person.InstanceCount
        type.SetField("InstanceCount", 2);
        AssertTrue(2 == type.GetField<int>("InstanceCount"));

        // Let's invoke Person.IncreaseCounter() static method to increase the counter
        // In fact, let's chain the calls to increase 2 times
        type.Invoke("IncreaseInstanceCount")
            .Invoke("IncreaseInstanceCount");
        AssertTrue(4 == type.GetField<int>("InstanceCount"));

        // Now, let's retrieve Person.InstanceCount via the static method GetInstanceCount
        AssertTrue(4 == type.Invoke<int>("GetInstanceCount"));

        // If we're not interested in the return (e.g. only in the side effect), 
        // we don't have to specify the type parameter (and can chain the result).  
        AssertTrue(4 == type.Invoke("GetInstanceCount")
                            .Invoke("GetInstanceCount")
                            .Invoke<int>("GetInstanceCount"));

        // Invoke method receiving ref/out params, we need to put arguments in an array
        var arguments = new object[] { 1, 2 };
        type.Invoke("Swap", 
            // Parameter types must be set to the appropriate ref type
            new[] { typeof(int).MakeByRefType(), typeof(int).MakeByRefType() },
            arguments);
        AssertTrue(2 == (int)arguments[0]);
        AssertTrue(1 == (int)arguments[1]);

        // Now, invoke the 2-arg constructor.  We don't even have to specify parameter types
        // if we know that the arguments are not null (Fasterflect will internally retrieve type info).
        obj = type.Construct(1, "Doe");

        // Due to struct type's pass-by-value nature, in order for struct to be used 
        // properly with Fasterflect, you need to convert it into a holder (wrapper) first.  
        // The call below does nothing if obj is reference type so when unsure, just call it.
        obj = obj.CreateHolderIfValueType();

        // id and name should have been set properly
        AssertTrue(1 == obj.GetField<int>("id"));
        AssertTrue("Doe" == obj.GetProperty<string>("Name"));

        // Let's use the indexer to retrieve the character at index 1
        AssertTrue('o' == obj.GetIndexer<char>(1));

        // If there's null argument, or when we're unsure whether there's a null argument
        // we must explicitly specify the param type array
        obj = type.Construct(new[] { typeof(int), typeof(string) }, new object[] { 1, null })
            .CreateHolderIfValueType();

        // id and name should have been set properly
        AssertTrue(1 == obj.GetField<int>("id"));
        AssertTrue(null == obj.GetProperty<string>("Name"));

        // Now, modify the id
        obj.SetField("id", 2);
        AssertTrue(2 == obj.GetField<int>("id"));
        AssertTrue(2 == obj.GetProperty<int>("Id"));

        // We can chain calls
        obj.SetField("id", 3).SetProperty("Name", "Buu");
        AssertTrue(3 == obj.GetProperty<int>("Id"));
        AssertTrue("Buu" == obj.GetProperty<string>("Name"));
         
        // How about modifying both properties at the same time using an anonymous sample
        obj.SetProperties(new {
                                  Id = 4, 
                                  Name = "Nguyen"
                              });
        AssertTrue(4 == obj.GetProperty<int>("Id"));
        AssertTrue("Nguyen" == obj.GetProperty<string>("Name"));

        // Let's have the folk walk 6 miles (and try chaining again)
        obj.Invoke("Walk", 1).Invoke("Walk", 2).Invoke("Walk", 3);

        // Double-check the current value of the milesTravelled field
        AssertTrue(6 == obj.GetField<int>("milesTraveled"));

        // Construct an array of 10 elements for current type
        var arr = type.MakeArrayType().Construct(10);

        // Get & set element of array
        obj = type.Construct();
        arr.SetElement(4, obj).SetElement(9, obj);

        if (isStruct) // struct, won't have same reference
        {
            AssertTrue(obj.Equals(arr.GetElement<object>(4)));
            AssertTrue(obj.Equals(arr.GetElement<object>(9)));
        }
        else 
        {
            AssertTrue(obj == arr.GetElement<object>(4));
            AssertTrue(obj == arr.GetElement<object>(9));
        }

        // Remember, struct array doesn't have null element 
        // (instead always initialized to default struct)
        if (!isStruct)
        {
            AssertTrue(null == arr.GetElement<object>(0));
        }
    }

    private static void ExecuteCacheApi(Type type)
    {
        var range = Enumerable.Range(0, 10).ToList();

        // Let's cache the getter for InstanceCount
        StaticAttributeGetter count = type.DelegateForGetStaticField("InstanceCount");

        // Now cache the 2-arg constructor of Person and playaround with the delegate returned
        int currentInstanceCount = (int)count();
        ConstructorInvoker ctor = type.DelegateForConstruct(new[] { typeof(int), typeof(string) });
        range.ForEach(i =>
        {
            object obj = ctor(i, "_" + i).CreateHolderIfValueType();
            AssertTrue(++currentInstanceCount == (int)count());
            AssertTrue(i == obj.GetField<int>("id"));
            AssertTrue("_" + i == obj.GetProperty<string>("Name"));
        });

        // Whatever thing we can do with the normal API, we can do with the cache API.
        // For example:
        AttributeSetter nameSetter = type.DelegateForSetProperty("Name");
        AttributeGetter nameGetter = type.DelegateForGetProperty("Name");

        object person = ctor(1, "Buu").CreateHolderIfValueType();
        AssertTrue("Buu" == nameGetter(person));
        nameSetter(person, "Doe");
        AssertTrue("Doe" == nameGetter(person));

        // Another example
        person = type.Construct().CreateHolderIfValueType();
        MethodInvoker walk = type.DelegateForInvoke("Walk", new[] { typeof(int) });
        range.ForEach(i => walk(person, i));
        AssertTrue(range.Sum() == person.GetField<int>("milesTraveled"));
    }

    public static void AssertTrue(bool expression)
    {
        if (!expression)
            throw new Exception("Not true");
        Console.WriteLine("Ok!");
    }
}