简体   繁体   中英

Should I created class or create if?

I have a situation:

I nee to do something with a class.

What should be more efficiente, modify the method this way witf IFs or created methos for each action?

public value Value(int command)
        {
            if (command == 1)
            {
                DoSomething1();
            }

            if (command == 2)
            {
                DoSomething2();
            }
            else
            {
                return empty();
            }


        }

There are going to be like 50 o more of this commands. Whats isbetter in terms of performance on execution and size of the exectuable?

At a high-level, it looks like you're trying to implement some kind of dynamic-dispatch system? Or are you just wanting to perform a specified operation without any polymorphism? It's hard to tell.

Anyway, based on the example you've given, switch block would be the most performant, as the JIT compiler converts it into an efficient hashtable lookup instead of a series of comparisons, so just do this:

enum Command { // observe how I use an enum instead "magic" integers
    DoSomethingX = 1,
    DoSomethingY = 2
}

public Value GetValue(Command command) {
    switch(command) {
        case Command.DoSomethingX: return DoSomethingX();
        case Command.DoSomethingY: return DoSomethingY();
        default: return GetEmpty();
    }
}

I also note that the switch block also means you get more compact code.

This isn't a performance problem as much as it is a paradigm problem.

In C# a method should be an encapsulation of a task. What you have here is a metric boatload of tasks, each unrelated. That should not be in a single method. Imagine trying to maintain this method in the future. Imagine trying to debug this, wondering where you are in the method as each bit is called.

Your life will be much easier if you split this out, though the performance will probably make no difference.

Although separate methods will nearly certainly be better in terms of performance, it is highly unlikely that you should notice the difference. However, having separate methods should definitely improve readability a lot, which is a lot more important.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM