简体   繁体   English

我应该创建类还是创建?

[英]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? 哪种方法更有效,用IF修改方法或为每个操作创建方法?

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. 该命令将多出50 o。 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: 无论如何,根据您给出的示例,switch块将是性能最高的,因为JIT编译器将其转换为有效的哈希表查找,而不是一系列比较,因此只需执行以下操作:

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. 我还注意到, switch块还意味着您可以获得更紧凑的代码。

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. 在C#中,方法应该是任务的封装。 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. 但是,使用单独的方法肯定会大大提高可读性,这更重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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