No, not answered there ↑
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 them in other languages so I'm also used to them in some way. Is there anything that speaks against using them ? Performance is the first key point for me. Would it drop ?
Example code:
class Program
{
// overloading
private static void test1(string text1)
{
Console.WriteLine(text1 + " " + "world");
}
private static void test1(string text1, string text2)
{
Console.WriteLine(text1 + " " + text2);
}
// optional parameters
private static void test2(string text1, string text2 = "world")
{
Console.WriteLine(text1 + " " + text2);
}
static void Main(string[] args)
{
test1("hello");
test1("hello", "guest");
test2("hello"); // transforms to test2("hello", "world"); ?
test2("hello", "guest");
Console.ReadKey();
}
}
I measured the time needed for a few millions overload calls and optional parameter calls.
- optional parameters with strings: 18 % slower (2 parameters, release)
- optional parameters with ints: <1 % faster (2 parameters, release)
(And maybe compilers optimize or will optimize those optional parameter calls in future ?)
I just did a quick test and the compiler optimizes the code. This basic example Main method.
Compiles to this so the optional params are filled in by the compiler.
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.
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.