重载或可选参数之间的性能差异?

2024-01-29

我想知道是否应该在 C# 中使用可选参数。到目前为止,我总是重载方法。但可选参数也很好,更干净,代码更少。我在其他语言中使用它们,所以我在某种程度上也习惯了它们。有什么反对使用它们的吗?性能对我来说是第一个关键点。会掉吗?


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.
  • 带字符串的可选参数:18 %slower(2个参数,释放)
  • 带整数的可选参数:faster(2个参数,释放)

(也许编译器会优化或will将来优化那些可选参数调用?)


我刚刚做了一个快速测试,编译器优化了代码。这个基本示例 Main 方法。

public static void OptionalParamMethod(bool input, string input2 = null)
{
}

public static void Main(string[] args)
{
    OptionalParamMethod(true);
    OptionalParamMethod(false, "hello");
}

编译为此,以便编译器填充可选参数。

public static void Main(string[] args)
{
    OptionalParamMethod(true, null);
    OptionalParamMethod(false, "hello");
}

至于性能,您可能会认为可选参数有一点优势,因为只有一个方法调用,而不是像通常对重载方法那样的链式方法调用。下面的代码是编译输出以显示我正在谈论的内容。这不同之处 https://gist.github.com/iwantedue/7150746虽然这是相当学术性的,但我怀疑你在实践中是否会注意到。

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");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

重载或可选参数之间的性能差异? 的相关文章

随机推荐