【发布时间】:2013-10-25 06:47:30
【问题描述】:
我想知道我是否应该在 C# 中使用可选参数。直到现在我一直在重载方法。但是可选参数也很好,更简洁,代码更少。而且我在其他语言中使用它们,所以我也以某种方式习惯了它们。有什么反对使用它们的吗?性能对我来说是第一个关键点。会掉吗?
示例代码:
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();
}
}
我测量了数百万次重载调用和可选参数调用所需的时间。
- 带字符串的可选参数:18 % slower(2 个参数,发布)
- 带整数的可选参数:更快(2 个参数,发布)
(也许编译器会优化或将在未来优化那些可选参数调用?)
【问题讨论】:
-
在stackoverflow.com/questions/3581747/…中回答的关于超载的完美问题
标签: c# performance overloading optional-parameters