2

Using strongly type names allows for refactor friendly code. Referencing names of properties, types, etc... generally involves reflection which adds overhead which in performance critical applications can be a problem.

Given the following code:

Console.WriteLine( "{0} is now running", typeof( Program ).Name );
Console.WriteLine( "{0} is now shutting down", typeof( Program ).Name );

Is there a way you can skip the reflection during execution? Is there a way to actually make the compiled code execute without the reflection calls?

Console.WriteLine( "{0} is now running", "Program" );
Console.WriteLine( "{0} is now shutting down", "Program" );

I've tried to use Reflection.Emit(), but can't quite seem to get what would be needed. Any suggestions or ideas would be great.

Jamin
  • 71
  • 2
  • 7

2 Answers2

2

The typeof operator and Type.Name property are both actually quite efficient. In this case, the overhead of Console.WriteLine vastly outweighs it.

For other types of code using "sneaky tricks" to avoid weakly-typed reflection (e.g. strings), such as using expression trees to simulate a methodof or fieldof operator, you can store the result in a static readonly field of a class, so they only need to be computed once.

Community
  • 1
  • 1
Sam Harwell
  • 92,171
  • 18
  • 189
  • 263
1

You could easily use a variable to hold the value. That is, at startup:

string programName = typeof(Program).Name;

And then use programName wherever you need it.

The case you show is obviously a contrived example, as I doubt that you're worried about the runtime efficiency of a couple Console.WriteLine calls.

Without a more concrete example, it's really hard to give specific useful suggestions.

Jim Mischel
  • 122,159
  • 16
  • 161
  • 305