77

I recently created an interface layer to distinguish the DataAccessProvider from our Business logic layer. With this approach we can change our choice of DataAccessProvider whenever we want by changing the values in the Web/App.Config. (more details can be given if needed).

Anyway, to do this we use reflection to accomplish our DataProvider class on which we can work.

/// <summary>
/// The constructor will create a new provider with the use of reflection.
/// If the assembly could not be loaded an AssemblyNotFoundException will be thrown.
/// </summary>
public DataAccessProviderFactory()
{
    string providerName = ConfigurationManager.AppSettings["DataProvider"];
    string providerFactoryName = ConfigurationManager.AppSettings["DataProviderFactory"];
    try
    {
        activeProvider = Assembly.Load(providerName);
        activeDataProviderFactory = (IDataProviderFactory)activeProvider.CreateInstance(providerFactoryName);
    }
    catch
    {
        throw new AssemblyNotFoundException();
    }
}

But now I'm wondering how slow reflection is?

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
user29964
  • 15,740
  • 21
  • 56
  • 63

7 Answers7

87

In most cases: more than fast enough. For example, if you are using this to create a DAL wrapper object, the time taken to create the object via reflection will be minuscule compared to the time it needs to connect to a network. So optimising this would be a waste of time.

If you are using reflection in a tight loop, there are tricks to improve it:

  • generics (using a wrapper where T : new() and MakeGenericType)
  • Delegate.CreateDelegate (to a typed delegate; doesn't work for constructors)
  • Reflection.Emit - hardcore
  • Expression (like Delegate.CreateDelegate, but more flexible, and works for constructors)

But for your purposes, CreateInstance is perfectly fine. Stick with that, and keep things simple.


Edit: while the point about relative performance remains, and while the most important thing, "measure it", remains, I should clarify some of the above. Sometimes... it does matter. Measure first. However, if you find it is too slow, you might want to look at something like FastMember, which does all the Reflection.Emit code quietly in the background, to give you a nice easy API; for example:

var accessor = TypeAccessor.Create(type);
List<object> results = new List<object>();
foreach(var row in rows) {
    object obj = accessor.CreateNew();
    foreach(var col in cols) {
        accessor[obj, col.Name] = col.Value;
    }
    results.Add(obj);
}

which is simple, but will be very fast. In the specific example I mention about a DAL wrapper—if you are doing this lots, consider something like dapper, which again does all the Reflection.Emit code in the background to give you the fastest possible but easy to use API:

int id = 12345;
var orders = connection.Query<Order>(
    "select top 10 * from Orders where CustomerId = @id order by Id desc",
    new { id }).ToList();
ErikE
  • 48,881
  • 23
  • 151
  • 196
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 2
    If someone wants to see how the reflection emit works for accessing fields (it's not too complicated) See: http://sharpanalytics.blogspot.de/2012/08/dynamic-methods-for-accessing-fields.html – Daniel Bişar Sep 11 '12 at 12:34
  • @Marc: I've been using reflection to get method, class name of current method to log the error in try-catch. basically to avoid hardcoding the function name while logging error. Do i need to worry? – Sangram Nandkhile Dec 18 '15 at 06:33
  • 1
    @Sangram probably not, no – Marc Gravell Dec 18 '15 at 07:38
21

Its slower compared to non-reflective code. The important thing is not if its slow, but if its slow where it counts. For instance, if you instantiate objects using reflection in web environment where expected concurency can rise up to 10K, it will be slow.

Anyway, its good not to be concerned about performance in advance. If things turns out to be slow, you can always speed them up if you designed things correctly so that parts that you expected might be in need of optimisation in future are localised.

You can check this famous article if you need speed up:

Dynamic... But Fast: The Tale of Three Monkeys, A Wolf and the DynamicMethod and ILGenerator Classes

Ryan
  • 2,948
  • 3
  • 30
  • 41
majkinetor
  • 8,730
  • 9
  • 54
  • 72
11

Here are some links that might help:

Ruben Steins
  • 2,782
  • 4
  • 27
  • 48
  • 9
    Don't be shocked. The longest time measured was 22 seconds for a million iterations. 22 *micro*seconds per call for the worst case. Unless you're creating a huge number of these objects, it's really not a big deal. Of course, if you *are* creating a huge number of these objects, then it might be a big deal, but as Marc notes it's still going to be swamped by the database connection and query times. Don't be freaked out by "x times as slow" articles unless you know it's performance-critical. – itowlson Apr 21 '09 at 08:22
  • I agree, even though it is slower, for most applications, the performance penalty will not outweigh the benefits of using Reflection. – Ruben Steins Apr 21 '09 at 08:25
8

I thought I'd do a quick test to demonstrate how slow reflection is compared to without.

With Reflection

  • Instantiating 58 objects by iterating through each of their Attributes and matching
  • Total Time: 52254 nanoseconds

    while (reader.Read()) {
        string[] columns = reader.CurrentRecord;
        CdsRawPayfileEntry toAdd = new CdsRawPayfileEntry();
        IEnumerable<PropertyInfo> rawPayFileAttributes = typeof(CdsRawPayfileEntry).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(CustomIndexAttribute)));
        foreach (var property in rawPayFileAttributes) {
            int propertyIndex = ((CustomIndexAttribute)property.GetCustomAttribute(typeof(CustomIndexAttribute))).Index;
            if (propertyIndex < columns.Length)
                property.SetValue(toReturn, columns[propertyIndex]);
            else
                break;
        }
    }
    

Without Reflection

  • Instantiating 58 Objects by creating a new object
  • Total Time: 868 nanoseconds

        while (reader2.Read()) {
            string[] columns = reader2.CurrentRecord;
            CdsRawPayfileEntry toAdd = new CdsRawPayfileEntry() {
                ColumnZero = columns[0],
                ColumnOne = columns[1],
                ColumnTwo = columns[2],
                ColumnThree = columns[3],
                ColumnFour = columns[4],
                ColumnFive = columns[5],
                ColumnSix = columns[6],
                ColumnSeven = columns[7],
                ColumnEight = columns[8],
                ColumnNine = columns[9],
                ColumnTen = columns[10],
                ColumnEleven = columns[11],
                ColumnTwelve = columns[12],
                ColumnThirteen = columns[13],
                ColumnFourteen = columns[14],
                ColumnFifteen = columns[15],
                ColumnSixteen = columns[16],
                ColumnSeventeen = columns[17]
            };
        }
    

Albeit, not completely fair since the reflection also has to retrieve a specific attribute of every property 58*18 times on top of creating a new object via reflection, but it at least provides some perspective.

Levi Fuller
  • 13,631
  • 4
  • 38
  • 44
5

Reflection is not THAT slow. Invoking a method by reflection is about 3 times slower than the normal way. That is no problem if you do this just once or in non-critical situations. If you use it 10'000 times in a time-critical method, I would consider to change the implementation.

Enyra
  • 17,542
  • 12
  • 35
  • 44
  • If this is true, I really like this statement. "Invoking a method by reflection is about 3 times slower than the normal way." Do you have any references? – Jonathon Reinhart May 01 '12 at 15:09
  • 1
    Uf my post is about 3 years old, I cant remeber from where I got this information. – Enyra May 02 '12 at 13:50
  • I converted a data access layer from the FieldInfo and PropertyInfo GetValue SetValue to the compiled expression. The time it took to read 30,000 rows with 40 columns went from 4 seconds down to 1 second. However, in a side-by-side comparison, reflection is between 200 and 250 times slower than a compiled expression when setting and getting values. – Loathing Jul 19 '14 at 08:44
3

Other than following the links given in other answers and ensuring you're not writing "pathalogically bad" code then for me the best answer to this is to test it yourself.

Only you know where you bottle necks are, how many times your reflection code will be user, whether the reflection code will be in tight loops etc. You know your business case, how many users will access your site, what the perf requirements are.

However, given the snippet of code you've shown here then my guess would be that the overhead of reflection isn't going to be a massive problem.

VS.NET web testing and performance testing features should make measuring the performance of this code pretty simple.

If you don't use reflection, what will your code look like? What limitations will it have? It may be that you can't live with the limitations that you find yourself with if you remove the reflection code. It might be worth trying to design this code without the reflection to see if it's possible or it the alternative is desirable.

Martin Peck
  • 11,440
  • 2
  • 42
  • 69
0

I was doing somethign similar until I started playing with IoC. I would use a Spring object definition to specify the data provider - SQL, XML, or Mocks!

n8wrl
  • 19,439
  • 4
  • 63
  • 103
  • Spring.net is quite capable of updating dependencies at runtime. If you update the config file and reload an instance from the factory, you'll get a reference to the updated instance. (Note that this does not work if you load the config from app.config, only if you use a separate spring XML file. – Jacob Jun 11 '09 at 14:38