Question

I've seemed to bump my head into the following

I understand that reflection can be costly when run at an at lib basis, with no caution thrown into the wind. How costly is .NET reflection?

But say I've got the following, and I intend to use it on my web API endpoints. like so:

  public AnotherDto Get(int someId)
  {
      var item = this.repo.FindAll(o => o.Id == someId)
                          .Take(1).Map<SomeDto>()
                          .FirstOrDefault();   

      var result = this.otherRepo
                       .FindAll(o => o.Id == item.Id)
                       .Map<AnotherDto>();    

      return result;
  }

Where Map<>()

public static IEnumerable<U> Map<U>(this IEnumerable<object> e)
    {
        var method = typeof(EntityExtensions).GetMethods(BindingFlags.Static | BindingFlags.Public)     
        .Where(m => m.Name == "Map" && m.GetGenericArguments().Length == 2)
        .Single();
        method = method.MakeGenericMethod(e.GetType().GetGenericArguments()[0], typeof(U));

        return method.Invoke(null, new object[] { e}) as IEnumerable<U>;
    }

Is this something that would be seen as code that would knock back performance to such an extent as to warrant not using it?

Was it helpful?

Solution

Firstly, chances are that this will not be the part of your application that is your bottleneck. For example, your use of the repository pattern suggests that you are talking to a database. This will be significantly slower than the code posted here. Profile your application and see what is slow and therefore worth spending time optimising.

Seocndly, to address your code, the only potential issue you should be aware of is that as you are returning an IEnumerable it could be evaluated multiple times which would cause the code to be run multiple times. To mitigate the added complexity this adds you should cache the result so that it will only get called once.

OTHER TIPS

Cache the method and then in the Map just invoke it. Then the reflection performance hit will be only once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top