If I implement an interface in a class, that does absolutely nothing, does it slow down code it is called from? Will example 2 (NoLogger) have any influence of the speed of the code, it is used in?
Example code:
interface ILogger{
void Write(string text);
}
class TextLogger : ILogger {
public void Write(string text){
using (var sw = new StreamWriter(@"C:\log.txt"))
{
sw.WriteLine(text);
}
}
}
class NoLogger : ILogger{
public void Write(string text){
//Do absolutely nothing
}
}
Implementation 1, TextLogger
void Main(){
ILogger tl = new TextLogger();
for (int i = 0; i < 100; i++)
{
tl.Write(i.ToString());
}
}
Implementation 2, NoLogger
void Main(){
ILogger tl = new NoLogger();
for (int i = 0; i < 100; i++)
{
tl.Write(i.ToString());
}
}
Of course example 1 (textlogger) slows down execution of the code it is implemented in, because it actually does something.
But what about example 2? Is the compiler intelligent enough to figure out, that even though a class is instantiated and a method is called, there is absolutely no code that does anything down any path, and just ignores it at compile time?