I'm facing a little dilemma.
I need to repetitively call a given method on many instances of a type, that may or may not exist. Because the method's result will never change for any given instance, I'm caching its return value for future use so as to reduce the overhead and return early on subsequent calls, but still the part that actually does the work needs to call that method-that-may-not-exist:
var method = Context.Parent.GetType().GetMethod("typeHint");
if (method == null)
{
token = null;
_hasTypeHint = false;
return false;
}
var hint = ((dynamic)Context.Parent).typeHint() as VBAParser.TypeHintContext;
Catching/handling a RuntimeBinderException
was a major performance bottleneck, so I decided to reflect on the type in question to go and discover whether the method exists or not before calling it.
The specific type of Context.Parent
is unknown at compile-time, and the possible runtime types don't share a common interface that would have the typeHint()
method I'm looking for: I need to either invoke the reflected member, or cast to dynamic
and invoke it directly.
My commit message goes like this:
removed the possibility for RuntimeBinderException by reflecting on the context type to locate the method to use. Kept (dynamic) cast because deemed less expensive than reflection invoke.. could be wrong though.
Which one incurs the least overhead, and more importantly, why?
Aucun commentaire:
Enregistrer un commentaire