I just saw this line of C# code and I am wondering if it is expensive
Assembly assembly = useEntryAssembly ? Assembly.GetEntryAssembly() : Assembly.GetCallingAssembly();
I just saw this line of C# code and I am wondering if it is expensive
Assembly assembly = useEntryAssembly ? Assembly.GetEntryAssembly() : Assembly.GetCallingAssembly();
Unless you perform calls like that a lot, the expensiveness is rather minuscule and I wouldn't worry about it.
On my machine Assembly.GetEntryAssembly()
takes 164 ticks the first time and 7 the next on a random run in debug mode. Without diving too deep in with Reflector it seems to be caching the calls.
There are 2597734 ticks a second on my machine, so 164 vs 7 is still unimportant.
I don't know about performance, but it's a code smell depending on what you're going to use this Assembly
object for.
Since you can do typeof(Anything).Assembly
to find an assembly, you already know what assembly you're in without calling these. The typeof
keyword can be checked by the compiler, whereas the results of GetEntryAssembly
and GetCallingAssembly
can surprise you. (For instance, GetEntryAssembly
can be null
.)
It would help to know what information you need from this assembly - there could be a better way to retrieve it.
Unless you make these calls a lot, I wouldn't worry. In any case, there are some simple optimisations you could make.
For example, Assembly.GetEntryAssembly()
won't change during the lifetime of your process (for a given AppDomain), so there is no need to do this call repeatedly, even if you need to access it. You could replace it with:
private static Assembly _entryAssembly;
private Assembly ExecutingAssembly
{
get
{
if (_entryAssembly == null )
{
_assembly = Assembly.GetEntryAssembly();
}
return _entryAssembly
}
Now you don't have to worry how expensive this call is; although possibly, as a commenter on another answer remarks, maybe the framework actually does this for you.
[note: this is intentionally not a thread safe singleton - the worst case scenario is that you make the call to Assembly.GetEntryAssembly()
a few times if first accessed similtaneously by several thread - not worth trying to lock for this scenario IMHO]