Click here to Skip to main content
13,252,362 members (66,682 online)
Click here to Skip to main content
Add your own
alternative version


202 bookmarked
Posted 4 Dec 2012

Reflection optimization techniques

, 29 May 2013
Rate this:
Please Sign up or sign in to vote.
The article presents some .NET techniques for using Reflection optimally and efficiently.


Reflection is one of the very powerful features in the Microsoft .NET framework. It provides a rich set of APIs under the namespace System.Reflection for loading and handling assemblies and objects besides retrieving meta data information such as method information, property information, and attributes (annotations) dynamically at runtime.

Using Reflection indeed makes developers’ life easy, however it should be used to a minimum and in other words only when it is required; it impacts the performance to a great extent. There are different techniques that help using reflection in an efficient way.

Often times we use reflection without realizing the cost that it comes at. In this article we will look at some techniques that help in using reflection optimally.


In this article, we will discuss some of the techniques that can be used for either avoiding reflection completely or at least using it repetitively. In the remainder of the article we will look at some scenarios where reflection can be used effectively.

Scenario 1 – Dynamic invocation of a method

If the names of methods/members to be invoked on an object created at run time are known at the time of development then instead of using reflection for dynamically invoking them, use interfaces and call them statically.

Example of completely dynamic invocation

public void DynamicExecution()
    Type objType = Type.GetType("DynamicExecution.Test.DynamicClass");

    object obj = Activator.CreateInstance(objType);
    MethodInfo mInfo = objType.GetMethod("AddNumbers",
	new Type[] { typeof(int), typeof(int) });

    // Executing AddNumbers method dynamically on obj
    mInfo.Invoke(obj, new object[] { 1, 5 });

    PropertyInfo pInfo = objType.GetProperty("ID");

    // Set property ID dynamically on obj
    pInfo.SetValue(obj, "TEST_ID", null );


Disadvantages of using the above code are: 

  1. Every dynamic call to a method or property is several times more expensive than a static call to the same method or property.
  2. Type safety of method parameters and property values is not checked during compile time and code can break at runtime if the parameters provided are not of the appropriate types.
  3. Code is lengthier than the optimized code and hence less maintainable.

Example of optimized code

Public void OptimizedDynamicExecution()
    Type objType = Type.GetType("DynamicExecution.Test.DynamicClass");

    IDynamicClass obj = Activator.CreateInstance(objType) as IDynamicClass;

    if (null != obj)
        // Executing AddNumbers method statically on obj
        int result = obj.AddNumbers(1, 5);

        // Set property ID statically on obj
	// The code will not compile if value is assigned as "TEST_ID"
        obj.ID = 10; 

// Interface to be consumed by OptimizedDynamicExecution API
public interface IDynamicClass
    int ID { get; set; }

    int AddNumbers(int a, int b);

Benefits of using the above code are: 

  1. Fast execution speed as the method is executed statically.
  2. Type safety achieved by making use of an interface.
  3. The same interface can be used at other places as appropriate.
  4. Shorter code for making method calls, etc.

Scenario 2 – Reading custom attributes from a class

Custom attributes (Annotations) are used to provide additional information about an assembly, a class, or a member of a class, so if a class is decorated with an attribute that is required every time you create an instance of that class then it is advisable to cache that value in a static variable so that reflection is used only for the first instance and can be avoided for subsequent instances.

Following is an example of an entity class:

public class Employee : Entity
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public DateTime DOB { get; set; }


The above code is an example of an entity class Employee which corresponds to a table in the database called “Employees”. If you look at it carefully, the property Id is decorated with an attribute called PrimaryKey. All the members including the class itself that are decorated with attributes have some special meaning which is required by the consumer of this class for processing each of its instances.

In order to retrieve this information, we have to apply reflection to read the attributes (annotations) from this class. It will be very expensive if it is repeated for every instance of this class. A better idea from a performance perspective would be to read it only for the first time and cache it for all subsequent instances.

Example of retrieving attributes information dynamically for every instance

public class Entity
    public Entity()
        Type curType = this.GetType();

        // The following reflection code will be executed every time 
        // an instance of this class is created.
        object[] tableAttributes =
		curType.GetCustomAttributes(typeof(TableAttribute), true);

        if(null != tableAttributes && tableAttributes.Count() > 0)
            // Retrieve the attribute information

        // Use the attribute information here 

Disadvantages of using the above code are

  1. Every time an object of this class is created, the attribute information is dynamically retrieved using reflection.
  2. Retrieving attribute information using reflection is a very expensive operation.

Following example demonstrates the concept of caching attribute information for achieving better performance: 

// C# structure to hold table information
public struct TableInfo
    public string TableName;
    public string PrimaryKey;

In this example code below, the constructor looks up a static dictionary object for the existence of table information using the current entity class’ type as the key. It will not be found for the first time and that’s when the attribute information will be retrieved using reflection and be kept in the collection for subsequent retrievals. This is how we save the cost of reflection. 

public class Entity
    private static Dictionary<Type, TableInfo> tableInfoList = 
                                         new Dictionary<Type, TableInfo>();

    public Entity()
        Type curType = this.GetType();
        TableInfo curTableInfo;
        if (!tableInfoList.TryGetValue(curType, out curTableInfo))
            lock (this)
                // double check to ensure that an instance is not 
                // created before this lock
                if (!tableInfoList.TryGetValue(curType, out curTableInfo))
                    object[] tableAttributes =
			curType.GetCustomAttributes(typeof(TableAttribute), true);

                    if(null != tableAttributes && tableAttributes.Count() > 0)
                        curTableInfo = new TableInfo();
                        curTableInfo.TableName = ((TableAttribute) tableAttributes[0]).Name;

        // use curTableInfo here 

The example code above demonstrates how information can be retrieved from custom attributes once and be used for subsequent instances of the same class without having to run the reflection code every time. 

Benefits of using this technique are:

  1. Reflection is applied only for the first time and a cached copy of the information is used for all subsequent times.
  2. The cost of reflection is minimized by using the caching technique. 

Scenario 3 – Dependency Injection

Often times we need to inject dependencies in some pieces of code for decoupling the implementation logic of a particular functionality form the logic of its consumer so that the implementation can be provided by different providers at a later point of time. To handle this scenario we normally allow the user to configure the assembly and the class to be injected in the configuration file.

In such a scenario the application would require to load the assembly and dynamically create the instance of the dependency class using reflection every time it is needed; this operation is very expensive in terms of processing and would result in poor performance in case of heavy traffic to this part of the application.

Microsoft .NET light-weight code generation helps in resolving the problem of creating an instance of any object that is not known at design time. It provides a set of APIs under the namespace System.Reflection.Emit for creating assemblies, classes, and methods etc., programmatically.

This technique can be used for reducing the overhead of creating objects using reflection every time by creating a dynamic method that would statically create the instance of the required class. This method’s delegate can then be cached in a dictionary for subsequent invocations.

Following example demonstrates this concept  

// Contract for the dependency class
public interface ISecurityProvider
    bool ValidateUser(string userId, string password);
    List<User> GetUsersList();

// Actual implementation of the dependency class to be instantiated
public interface DefaultSecurityProvider : ISecurityProvider
    public bool ValidateUser(string userId, string password)
    public List<User> GetUsersIist()

Example of completely dynamic invocation

// Method that needs to create the instance of DefaultSecuirtyProvider
// class dynamically
private void CreateInstance()
    Type classType =
        Type.GetType("DefaultSecurityProvider, AssemblyName");
    // Follwoing code creates the instacne of dependency class
    // dynamically using reflection every time.
    ISecurityProvider employeeInstance = Activator.CreateInstance(classType) as ISecurityProvider;

Disadvantages of using the above code are: 

  1. Every time an instance of the dependency class is required, it will be created dynamically using reflection.
  2. Creating an object dynamically using reflection is a very expensive operation. 

Following code demonstrates how the cost of reflection can be avoided:  

// Method that needs to create the instance of DefaultSecuirtyProvider
// class dynamically
private void CreateInstance()
    Type classType = 
   Type.GetType("DefaultSecurityProvider, AssemblyName");

    // Following function returns the delegate for instantiating the required
    // object statically
    CreateInstanceDelegate createInstance = ObjectInstantiater(classType);

    // Executing the delegate for creating an instance of the dependency class
    ISecurityProvider employeeInstance = createInstance() as ISecurityProvider;

Following delegate will be used for mapping the method dynamically created using Microsoft .NET light weight code generation technique 

// Delegate for holding object instantiator method
public delegate object CreateInstanceDelegate(); 

Following dictionary object will hold the delegates of the methods dynamically created for instantiating dependency class objects

// Dictionary for holding object instantiator delegates
private static Dictionary<Type, CreateInstanceDelegate> 
    _createInstanceDelegateList = new Dictionary<Type, CreateInstanceDelegate>();

Following function creates a method programmatically at run time for instantiating the objects of a given type. 

// Function that creates the method dynamically for creating the instance
// of a given class type
public static CreateInstanceDelegate ObjectInstantiater(Type objectType)
    CreateInstanceDelegate createInstanceDelegate;

    if (!_createInstanceDelegateList.TryGetValue(objectType, 
        out createInstanceDelegate))
        lock (objectType)
            if (!_createInstanceDelegateList.TryGetValue(objectType, 
         out createInstanceDelegate))
                // Create a new method.        
                DynamicMethod dynamicMethod =
                    new DynamicMethod("Create_" + objectType.Name,
	           objectType, new Type[0]);

                // Get the default constructor of the plugin type
                ConstructorInfo ctor = objectType.GetConstructor(new Type[0]);

                // Generate the intermediate language.       
                ILGenerator ilgen = dynamicMethod.GetILGenerator();
                ilgen.Emit(OpCodes.Newobj, ctor);

                // Create new delegate and store it in the dictionary
                createInstanceDelegate = (CreateInstanceDelegate)dynamicMethod
                _createInstanceDelegateList[objectType] = createInstanceDelegate;
    return createInstanceDelegate; // return the object instantiator delegate

The above code demonstrates how an object of any class can be created statically that is not known at design time and only recognized by its interface (contract).

In the above example we created a proxy method dynamically using APIs provided in the System.Reflection.Emit namespace that creates the instance of the dependency class statically. Once this method is created we store it in a dictionary against the type of the dependency class as the key so that for all subsequent times we can pull this delegate from the dictionary and use it.

Benefits of using this technique are:

  1. The object of the dependency class is created statically using the Object instantiating method.
  2. This technique helps in avoiding reflection for object instantiation.  

Scenario 4 - Setting the property values of an ORM entity dynamically

In all ORM frameworks, there are entity classes that correspond to tables in the database. The framework applies reflection for reading the values of the properties (columns) and setting the values of the properties (columns) from each instance of an entity class. This operation is very expensive and could reduce performance to a great extant. This can be handled by generating dynamic methods in the same way as it was demonstrated in scenario 3, however in this example we will achieve this using a new feature introduced in .NET Framework 3.5 called Expression Trees.

Following example demonstrates this concept  

// Entity class Employees
public class Employees
    public int EmployeeID { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public DateTime BirthDate { get; set; }

// Employees list to be populated with data retrieved from the data reader
List<Employees> empList = new List<Employees>();  

Following code fills the list of employees from the data reader 

// Employees list to be populated with data retrieved from the data reader
List<Employees> empList = new List<Employees>();

using(SqlConnection con = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;
   Initial Catalog=Northwind;Integrated Security=True"))
    SqlCommand cmd = new SqlCommand("Select * from employees");
    cmd.Connection = con;

    // Call the ReadList method seding Employees as the type of entity
    // and the data reader as the parameter
    using (SqlDataReader reader = cmd.ExecuteReader())
        empList = ReadList<Employees>(reader);

Example of setting the property values of an entity class dynamically using reflection

// Method to be called for getting the list of entity class
// filled with data from the data reader. 
public List<T> ReadList<T>(SqlDataReader reader) where T : new()
    var list = new List<T>();

    while (reader.Read())
        T entity = new T();
        Type entityType = typeof(T);
        foreach(var entityProperty in entityType.GetProperties())
            // Using reflection for setting the value of each 
            // property of the entity.
            entityProperty.SetValue(entity, reader[entityProperty.Name], null);

    return list;

Disadvantages of using the above code are:

  1. Setting the properties of an object using reflection is a very heavy operation.
  2. The developer has to take care of type safety while setting the value of the property

The following example demonstrates how values can be read from an object of SqlDataReader and added to a list of an entity without having to write event static code as well as without applying reflection repeatedly.

Following function iterates through the data reader and populates a list of entities with relevant values

// Method to be called for getting the list of entity class
// filled with data from the data reader. 
public List<T> ReadList<T>(SqlDataReader reader)
    var list = new List<T>();  
    Func<SqlDataReader, T> readRow = GetReader<T>(); 

    while (reader.Read())
    return list;

Following dictionary holds the delegate of the method generated dynamically for populating the data table values into the entity list  

// Cache store for memorizing the delegate for later use
ConcurrentDictionary<Type, Delegate> ExpressionCache = 
                       new ConcurrentDictionary<Type, Delegate>();

Following method creates a function programmatically using Expression tree feature of Microsoft .NET. The dynamically generated function is saved as a delegate in a dictionary for later retrieval 

// Method for creating the dynamic funtion for setting entity properties
public Func<SqlDataReader, T> GetReader<T>()
    Delegate resDelegate;
    if (!ExpressionCache.TryGetValue(typeof(T), out resDelegate))
        // Get the indexer property of SqlDataReader 
        var indexerProperty = typeof(SqlDataReader).GetProperty("Item",
        new[] { typeof(string) });
        // List of statements in our dynamic method 
        var statements = new List<Expression>();
        // Instance type of target entity class 
        ParameterExpression instanceParam = Expression.Variable(typeof(T));
        // Parameter for the SqlDataReader object
        ParameterExpression readerParam =

        // Create and assign new T to variable. Ex. var instance = new T(); 
        BinaryExpression createInstance = Expression.Assign(instanceParam,

        foreach (var property in typeof(T).GetProperties())
            // instance.Property 
            MemberExpression getProperty =
            Expression.Property(instanceParam, property);
            // row[property] The assumption is, column names are the 
            // same as PropertyInfo names of T 
            IndexExpression readValue =
                Expression.MakeIndex(readerParam, indexerProperty,
                new[] { Expression.Constant(property.Name) });

            // instance.Property = row[property] 
            BinaryExpression assignProperty = Expression.Assign(getProperty,
                Expression.Convert(readValue, property.PropertyType));

        var returnStatement = instanceParam;

        var body = Expression.Block(instanceParam.Type,
            new[] { instanceParam }, statements.ToArray());

        var lambda =
        Expression.Lambda<Func<SqlDataReader, T>>(body, readerParam);
        resDelegate = lambda.Compile();

        // Cache the dynamic method into ExpressionCache dictionary
        ExpressionCache[typeof(T)] = resDelegate;
    return (Func<SqlDataReader, T>)resDelegate;

In the above code, we created a function dynamically using .NET expression tree feature that sets the values of an entity object after reading them from a SqlDataReader object passed to it as a parameter. This method is compiled and cached in a dictionary so that it can be used for all subsequent times without having to recreate it.

Benefits of using this technique are:

  1. The developer is not required to write code for setting values of any entity.
  2. The expression tree created for the method can be serialized and transferred across process boundaries.
  3. It is easier to create an expression tree using the .NET APIs rather than writing the IL code.


We looked at four scenarios where the reflection technique was used in an inappropriate way that leads to poor performance and we also looked the techniques that can be used for improving the performance by either using an alternative to reflection or using the caching mechanism for avoiding the use of reflection repetitively.

Caching technique used in this article ensures that the information is retrieved using reflection only once and used multiple times.

Dynamic code generation using Light weight code generation technique and Expression Trees help in creating static proxy methods to avoid reflection in scenarios such as instantiating objects and setting/getting property values etc.

Further Reading


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Jain, Ajay
Architect Symphony Teleca Corporation
India India
I am Ajay Jain, a Senior Architect with 16+ years of experience in Microsoft technologies. I work at Symphony Teleca Corporation, Bangalore. I specialize in technologies like Microsoft.Net, C#, SOA, Enterprise Architecture, SQL Server, JavaScript and Azure.

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
Lorin Felix10-Aug-15 23:28
memberLorin Felix10-Aug-15 23:28 
QuestionActivator.Createinstance is faster than your scenario 3 Pin
HM India24-Dec-14 8:10
memberHM India24-Dec-14 8:10 
AnswerRe: Activator.Createinstance is faster than your scenario 3 Pin
Jain, Ajay1-Jan-15 20:35
memberJain, Ajay1-Jan-15 20:35 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun11-Nov-14 23:42
memberHumayun Kabir Mamun11-Nov-14 23:42 
QuestionEven though your intent is correct, you're forgetting the most useful solution imo Pin
atlaste8-Nov-13 4:31
memberatlaste8-Nov-13 4:31 
AnswerRe: Even though your intent is correct, you're forgetting the most useful solution imo Pin
Jain, Ajay10-Nov-13 23:36
memberJain, Ajay10-Nov-13 23:36 
GeneralMy vote of 5 Pin
fredatcodeproject30-May-13 4:36
memberfredatcodeproject30-May-13 4:36 
GeneralMy vote of 5 Pin
Prasad Khandekar30-May-13 4:00
professionalPrasad Khandekar30-May-13 4:00 
GeneralAnother approach. Pin
db7uk30-May-13 0:44
professionaldb7uk30-May-13 0:44 
GeneralRe: Another approach. Pin
Jain, Ajay30-May-13 7:47
memberJain, Ajay30-May-13 7:47 
QuestionGetReader Pin
Maze29-May-13 9:50
memberMaze29-May-13 9:50 
AnswerRe: GetReader Pin
Jain, Ajay29-May-13 21:38
memberJain, Ajay29-May-13 21:38 
GeneralMy vote of 5 Pin
dgDavidGreene21-Apr-13 9:12
memberdgDavidGreene21-Apr-13 9:12 
GeneralRe: My vote of 5 Pin
Jain, Ajay22-Apr-13 8:47
memberJain, Ajay22-Apr-13 8:47 
QuestionInstantiate an object from a string Pin
Member 999425219-Apr-13 1:39
memberMember 999425219-Apr-13 1:39 
QuestionSome points to revise... Pin
Paulo Zemek17-Apr-13 7:41
memberPaulo Zemek17-Apr-13 7:41 
AnswerRe: Some points to revise... Pin
Jain, Ajay18-Apr-13 5:24
memberJain, Ajay18-Apr-13 5:24 
GeneralRe: Some points to revise... Pin
Paulo Zemek18-Apr-13 5:33
memberPaulo Zemek18-Apr-13 5:33 
BugRe: Some points to revise... Pin
Member 424077628-May-13 8:26
memberMember 424077628-May-13 8:26 
GeneralRe: Some points to revise... Pin
Jain, Ajay28-May-13 8:45
memberJain, Ajay28-May-13 8:45 
GeneralThx Pin
Champion·Chen27-Feb-13 17:03
memberChampion·Chen27-Feb-13 17:03 
GeneralMy vote of 5 Pin
Tim Grindley4-Feb-13 5:42
memberTim Grindley4-Feb-13 5:42 
QuestionClarification on speed measures Pin
Tim Grindley4-Feb-13 5:41
memberTim Grindley4-Feb-13 5:41 
Thanks for the article, it is a subject I have been looking at recently. I know this thread is now a couple of months old now but could you just clarify things regarding your optimized method. I took your code and applied it to one of my databases - it read 10,000 records (20 columns per row) in 112 ms as opposed to 1104 ms using straight reflection. So pretty good.

Took the opposite stance and did a single row read and the situation was reversed somewhat - time to build the cache etc etc, not surprising I guess.

As with a lot of things in IT the best method to solve a problem depends on what the problem is, so in your investigation and implementation of this approach did you come to any decision as to how you would implement this approach? ie use straight reflection for low numbers of records and the optimizied approach for larger blobs of data (assuming performance was your goal).

Was, or is it the fact that the time to read a single record using the optimzed approach so negligible that you used this approach throughout and you didn't want the code maintenance headache of two lots of code, or what?

My database test looked like 150 rows was the tilting point for equal timing. I guess I probably already know the answer but I would interested to hear from you as you have used it in anger.

Thanks for putting in the time to write this article.
AnswerRe: Clarification on speed measures Pin
Jain, Ajay4-Feb-13 21:41
memberJain, Ajay4-Feb-13 21:41 
GeneralRe: Clarification on speed measures Pin
Tim Grindley4-Feb-13 23:46
memberTim Grindley4-Feb-13 23:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171114.1 | Last Updated 30 May 2013
Article Copyright 2012 by Jain, Ajay
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid