I have a list of items implementing an interface. For the question, let’s use this example interface:
interface Person
{
void AgeAYear();
}
There are two classes
class NormalPerson : Person
{
int age = 0;
void AgeAYear()
{
age++;
//do some more stuff...
}
}
class ImmortalPerson : Person
{
void AgeAYear()
{
//do nothing...
}
}
For other reasons, I need them both of the list. But for this call, when I loop through my list of Persons, I may be calling empty functions. Will this have a performance impact? If so, how much? Will the empty function, for all intents and purposes, be optimized out?
NOTE: In the real example, the ImmortalPerson has other methods that do have code – it is not just an object that does nothing.
Highly unlikely to have a meaningful performance impact.
You can quantify it exactly for your specific code paths using a profiler. We can not, because we don’t know the code paths. We can guess, and tell you it almost surely doesn’t matter because this is extremely unlikely to be a bottleneck in your application (are you really sitting there calling
Person.AgeAYearin a tight loop?).Only you can find out precisely by getting out a profiler and measuring.
It’s certainly possible but it might not; it might even change in future version of the JITter, or change from platform to platform (different platforms have different JITters). If you really want to know, compile your application, and look at the disassembled JITted code (not the IL!).
But I’ll say this: this is almost surely, almost definitely not something worth worrying about or putting any time into. Unless you are calling
Person.AgeAYearin a tight loop in performance critical code, it’s not a bottleneck in your application. You could spend time on this, or you could spend time improving your application. Your time has an opportunity cost too.