在VB.NET中使用ElseIf或Case语句

ѺȐe*_*llү 0 vb.net performance if-statement case-statement

是否有任何一般性能指导用于何时使用Case而不是链ElseIf

请考虑以下示例......

        Dim lobjExample As Object = GetARandomDataTypeCrapExample()
        If lobjExample Is GetType(Boolean) Then
            ' Solve world hunger here 
        ElseIf lobjExample Is GetType(Byte) Then
            ' Solve world hunger here 
        ElseIf lobjExample Is GetType(Char) Then
            ' Solve world hunger here 
        ElseIf lobjExample Is GetType(Date) Then
            ' Solve world hunger here 
        ElseIf lobjExample Is GetType(Decimal) Then
            ' Solve world hunger here 
        ElseIf lobjExample Is GetType(String) Then
            ' Solve world hunger here 
        ElseIf lobjExample Is GetType(Integer) Then
            ' Solve world hunger here 
        ElseIf lobjExample Is GetType(Double) Then
            ' Solve world hunger here 
        ElseIf lobjExample Is GetType(Long) Then
            ' Solve world hunger here 
        ElseIf lobjExample Is GetType(SByte) Then
            ' Solve world hunger here 
        ElseIf lobjExample Is GetType(Short) Then
            ' Solve world hunger here 
        ElseIf lobjExample Is GetType(Single) Then
            ' Solve world hunger here 
        ElseIf lobjExample Is GetType(ULong) Then
            ' Solve world hunger here 
        ElseIf lobjExample Is GetType(UInteger) Then
            ' Solve world hunger here 
        ElseIf lobjExample Is GetType(UShort) Then
            ' Solve world hunger here 
        Else
            ' Cannot solve world hunger 
        End If
Run Code Online (Sandbox Code Playgroud)

这会更适合作为案例陈述吗?

Han*_*ant 7

VB.NET Select Case语句非常灵活.比同等的C#switch关键字要多得多.这完全是故意的,是语言背后的哲学的一部分.VB.NET对程序员友好,C#对机器友好.

.NET中间语言有一个专用的操作码来实现这些语句,Opcodes.Switch.如果跳转表是"完美的"并填充了所有插槽,它将在运行时被跳转到跳转表,非常快,没有if-then-else代码.

但它有一个实际的限制,跳转表条目必须在编译时知道.如果Case语句是常量表达式,那么它可以正常工作.C#编译器在switch语句中允许的类型.但是,这不能是Object.GetType()的值,"类型句柄"是在运行时生成的,其值将完全取决于之前的jitted.

因此VB.NET编译器执行程序员友好的事情并将您的Select Case语句转换为If-Then-Else语句链.完全像你手工编写的那种.使用Ildasm.exe工具自己查看.

所以不要吝啬你的风格,它没有任何区别.唯一你真的想找出一个查找表可以使其更快.A Dictionary(Of Type, Integer),现在您的Select Case语句将非常快,因为它可以使用优化版本.但随着字典的增加成本.只有你足够关心它才能检查.使用真实数据非常重要,合成测试往往无法正确测试所需的If-Then测试数量.Case语句的顺序非常重要,最有可能的匹配应该在最重要的位置.

或许值得注意的是即将发布的Select Case TypeOf语句.它只是语法糖,而不是perf.