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 ?)