Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 343
KainDefiant Avatar asked Mar 01 '26 03:03

KainDefiant


1 Answers

There will be a performance difference. It will be faster having typespecific methods, but unless it is to be done hundreds of times per second, it should not be a significant difference.

The more dynamic and generic you make methods and classes, the more CPU heavy it will be on the computer processing it. I guess if its being run on a slow computer it might make more of a difference.

As DavidG suggested, you could try to run performance tests yourself. You could store DateTime.Now before running a bunch of these methods and another test using the type testing of an object, and then output the difference with a new DateTime.Now after.

like image 91
Kasper Olesen Avatar answered Mar 03 '26 15:03

Kasper Olesen