Monday, March 18, 2013

Difference between If ElseIf Else and Select case

Q: Is there any difference between using If else for certain condition rather than using select case in case of performance vb.net or c#.net ?

Ans: No

Both the things are same. I will explain this with the help of example
I created a class in vb.net project with code like,

Public Class Class1
    Dim i As Integer = 1
    Dim x As String

    Public Sub cClass1()
        If i = 1 Then
            x = "ONE"
        ElseIf i = 2 Then
            x = "TWO"
        Else
            x = "NULL"
        End If
    End Sub

End Class

And compiled it and copied its IL code to a file.

And used select case instead of if else,



Public Class Class1
    Dim i As Integer = 1
    Dim x As String

    Public Sub cClass1()
        Select Case i
            Case 1
                x = "ONE"
            Case 2
                x = "TWO"
            Case Else
                x = "NULL"
        End Select
    End Sub

End Class
And compiled it and stored it in another text file.

And compared both files and there was no difference in MSIL code and it was.

.method public specialname rtspecialname 
        instance void  .ctor() cil managed
{
  // Code size       16 (0x10)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
  IL_0006:  nop
  IL_0007:  ldarg.0
  IL_0008:  ldc.i4.1
  IL_0009:  stfld      int32 cIfElseSelect.Class1::i
  IL_000e:  nop
  IL_000f:  ret
} // end of method Class1::.ctor

To prove this with another point. I used timer class to get the exact time of execution for select and if else cases and they took same time for execution.

So we can have any of the two methodologies which suits you.

Thanks

No comments:

Post a Comment