首页 > 解决方案 > C# - Is overloading methods with different types more performant than using type checking in a single method?

问题描述

Say I have this:

    public void DoThing (string text)
    {
        DoThingWithText(text);
    }

    public void DoThing (int number)
    {
        DoThingWithNumbers(number);
    }

And compare it to this:

    public void DoThing (object obj)
    {
        if (obj is string text)
            DoThingWithText(text);

        if (obj is int number)
            DoThingWithNumbers(number);
    }

Would there be a performance difference here, and if so how significant?

标签: c#performanceoverloadingtypechecking

解决方案


会有性能差异。使用特定于类型的方法会更快,但除非每秒执行数百次,否则差异不会很大。

您创建的方法和类越动态和通用,处理它的计算机上的 CPU 就越重。我想如果它在慢速计算机上运行它可能会产生更大的不同。

正如 DavidG 建议的那样,您可以尝试自己运行性能测试。您可以在运行一堆这些方法之前存储 DateTime.Now 并使用对象的类型测试进行另一个测试,然后使用新的 DateTime.Now 输出差异。


推荐阅读