I wonder if I should be using optional parameters in C#. Until now I was always overloading methods. But optional parameters are nice too, cleaner and less code. And I use t
I just did a quick test and the compiler optimizes the code. This basic example Main method.
public static void OptionalParamMethod(bool input, string input2 = null)
{
}
public static void Main(string[] args)
{
OptionalParamMethod(true);
OptionalParamMethod(false, "hello");
}
Compiles to this so the optional params are filled in by the compiler.
public static void Main(string[] args)
{
OptionalParamMethod(true, null);
OptionalParamMethod(false, "hello");
}
As for performance you could argue optional parameters have a slight advantage as there is only a single method call rather than chained method calls like you would normally have for an overloaded method. The code below is compiled output to show what I am talking about. The difference is quite academic though and I doubt you would ever notice in practice.
public static void Main(string[] args)
{
OptionalParamMethod(true, null);
OptionalParamMethod(false, "hello");
OverloadParamMethod(true);
OverloadParamMethod(false, "hello");
}
public static void OptionalParamMethod(bool input, [Optional, DefaultParameterValue(null)] string input2)
{
Console.WriteLine("OptionalParamMethod");
}
public static void OverloadParamMethod(bool input)
{
OverloadParamMethod(input, null);
}
public static void OverloadParamMethod(bool input, string input2)
{
Console.WriteLine("OverloadParamMethod");
}
Neither overloading nor optional parameters will in themselves cause any changes in performance. As David Ewen noted, the C# compiler produces IL that does not know about optional parameters (this is the sources of some versioning bugs that come from optional parameters on types which can be literal).
As for overloading. C# is a (mostly) statically typed language. The compiled code directly references the address of the appropriate method. There is a small performance hit when overloading AT COMPILE time. In C++ in fact, overloading is done by a process called "name mangling" where each overload at compile time is given a unique name.
However there are cases where overloading CAN impact performance. But these are pretty obvious, like during reflection and in dynamic typed code.
It sounds like you are confused about the performance hit of virtual/abstract functions. In order for the .net runtime to resolve the correct function, there is an extra step which looks up the particular type's implementation of that method.