5

I think some code using reflection can be optimized (I'm not sure we can call it optimize) at compile time.

  • For example, System.Reflection.MethodInfo.GetCurrentMethod always returns the same value when it is called in the same method.

  • Also, accessing a class info using class name represented constant string has no reason to be done at run time.

I have tested it and I got a result that shows a code with reflection is about 300x slower than one without reflection.

Are there any compile option(s) that enable what I want?

Ruskin
  • 5,721
  • 4
  • 45
  • 62
12412316
  • 725
  • 7
  • 17
  • Take a look in [this document](http://msdn.microsoft.com/en-us/magazine/cc163759.aspx) regarding reflection performance. – Matthijs Jun 20 '14 at 08:26
  • What you're asking about sounds similar to *caller information attributes* (http://msdn.microsoft.com/en-us/library/hh534540(v=vs.110).aspx). Unfortunately there doesn't appear to be an equivalent for current method info, so your best bet will be simply caching the `GetCurrentMethod` return value. – Kirill Shlenskiy Jun 20 '14 at 08:31
  • I can't think of a specific case for example 1 but for the second the information certainly can change (if you update the DLL hosting the class for example) – Ronan Thibaudau Jun 20 '14 at 09:14
  • You completely overlook [this](http://stackoverflow.com/a/4045073/17034). The inlining optimization makes GetCurrentMethod() return something else. The only point of using a string is that you *don't* know what class it might be. The compiler of course doesn't either. Sure, replacing code that takes a nanosecond, like a method call, with Reflection is inevitably going to be a lot slower. – Hans Passant Jun 20 '14 at 11:09

3 Answers3

2

For the case of System.Reflection.MethodInfo.GetCurrentMethod. This is usually used for getting the name of the current method call.

If this is the use case

public void Foo()
{
    var method = System.Reflection.MethodInfo.GetCurrentMethod();
    Log.Log(string.Format("I is inside of {0}", method.Name));
}

Then you should replace this with

public static MemberName([CallerMemberName] memberName = null)
{
    return memberName;
}

public void Foo()
{
    Log.Log(string.Format("I is inside of {0}", MemberName()));
}
Aron
  • 15,464
  • 3
  • 31
  • 64
0

Reflection in .net is indeed painfully slow. There is nothing much one can do about this.

On the other hand, it may be suitable for you to use 'fasterflect' http://fasterflect.codeplex.com/, which implements several features of the built-in .net reflection with improved performance.

Peter Brennan
  • 1,366
  • 12
  • 28
0

All reflection can be cached and execute once. I recommand it to preserve performance and extensibility. (valuate static fields for exemple in static constructor)

Method like getcurrent...thing is a lazy shortcup code. You know where you are... You can keep yours methodinfo in static private field to use them.

Teter28
  • 504
  • 5
  • 8