So I have read this article C# Overloads which says that you can use overloaded methods to eliminate complexity and enhance performance and they provide the following example:
using System;
class Program
{
public static void Main()
{
ShowString(string.Empty);
ShowString("Category");
}
static void ShowString(string value)
{
if (value == string.Empty)
{
Console.WriteLine("Popular");
}
else
{
Console.WriteLine(value);
}
}
}
which they then rewrite using overloads:
using System;
class Program
{
public static void Main()
{
ShowString();
ShowString("Category");
}
static void ShowString()
{
// Send default argument to overload.
ShowString("Popular");
}
static void ShowString(string value)
{
// We don't need an if check here, which makes
// ... calling this method directly faster.
Console.WriteLine(value);
}
}
Would using the overloads variant provide better performance results than using a method with a default parameter value?
like:
using System;
class Program
{
public static void Main()
{
ShowString();
ShowString("Category");
}
static void ShowString(string value = "Popular")
{
// We don't need an if check here, which makes
// ... calling this method directly faster.
Console.WriteLine(value);
}
}
or is the last block of code the equivalent of the first block of code?
No, default parameters are at least as fast as overloads, because your last example compiles to:
Your second example (using overloads) would (if built for Release instead of Debug) likely be inlined at runtime so that the performance would be the same as the last example (default parameters).
The example is kind of silly, since the cost of
value == string.Emptyis practically nothing, but I suppose it serves to illustrate the point. However, and this is probably the most important bit you should take from this answer: You should always go for clearer/more maintainable code before premature optimization, so usability should be the overriding factor in determining what you should use in a given situation.