需要知道开关性能C# [英] Need to know switch performance C#

查看:88
本文介绍了需要知道开关性能C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设某个方法有一个开关

Suppose there is a switch on some method like

static string switchExample(string abc){
    switch(abc.ToUpper()) {
        case "123":
            return "Numeric";
        case "ab":
            return "Alphabets";
        default:
            return "symbol";
    }
}

现在这里我需要知道是否有任何性能问题使用多个退出点(返回每个案例),就像我在给定的代码,而不是一次传递更新的值,通过在开始时做一些临时字符串,并填充相应的案例匹配。

Now here I need to know is there any performance issue to use multiple points of exit(return on each case) like i did in given code rather to pass updated value at one time by making some temp string at the start and filling it with corresponding case match.

推荐答案


现在这里我需要没有是否有任何性能问题使用多个
退出点

Now here i need to no is there any performance issue to use multiple points of exit

您的问题是过早优化的缩影。

Your question is the epitome of premature optimization.

我的建议,如果你真的想知道,是以两种方式写出方法 - 一次在每种情况下用 return 语句,在开关后用一次返回一次语句。

My suggestion, if you really want to know, is to write the method out both ways - once with return statements in each case and once with a single return after the switch statement. Then decompile each to intermediate language for comparison.

如果不通过分析进行实际测量,您仍然无法对性能做任何声明。

You still won't be able to make any certain statement about performance without doing actual measurement by profiling.

但是,我认为任何差异(如果有的话)都是非常微不足道的。最终结果应该只是将值与常量字符串进行比较,并且在匹配时推送值和堆栈并返回。

But, I think it's quite safe to say that any difference, if any, will be extremely miniscule. The end result should be nothing more than comparing the value to the constant strings, and when matched pushing the value and the stack and returning. The compiler will likely optimize away the assignment to a temporary variable, seeing that it will only be used as a return value.

此外,一些switch语句被显着地优化了编译器。请参见 http://stackoverflow.com/a/395965/224087 http://stackoverflow.com/a/126507/224087 了解开关语句性能和优化的更多信息。

Furthermore, some switch statements are significantly optimized by the compiler. See http://stackoverflow.com/a/395965/224087 and http://stackoverflow.com/a/126507/224087 for more information of switch statement performance and optimization.

这个代码你怀疑的性能只会是一两个CPU操作 - 一个真正小的时间来关心。

This code you are questioning the performance of will only be a handful or two of CPU operations - a truly tiny amount of time to be concerned with.

这篇关于需要知道开关性能C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆