vb.netcastingperformanceimplicitdirectcast

Implicit VB performance question


Sometimes I have to implement an interface or inherit a virtual (MustInherit) that the base method expects an object, whilst I know that the value I will be passing will always be an Integer for example.

What should be the best performance from the examples below:

Public Sub DoSomething(ByVal obj As Object)
    'option 1:
    Dim x As Integer = obj

    'option 2:
    Dim y = DirectCast(obj, Integer)
End Function

Considerations:

Note: Please don't comment with "Why wouldn't you want to implement it in different way" etc. etc. My question is not how to do this, I didn't find an example of how to ask it, my question is just what option should be the rightes, and what will cost more performance.


Solution

  • Your Option 1 is still casting -- in fact, it's doing more than that, it's performing a conversion. For example, if obj is the string "1", Option 1 will convert it to the integer 1, whereas Option 2 will fail with an InvalidCastException. (In the good old days, this was known as "evil type coercion," which sounds way cooler than implicit conversion, but also highlights the potential danger that this approach can disguise errors and result in unanticipated behaviour.)

    So Option 1 will probably be slightly less performant because it's doing a bit more work (conversion as opposed to a plain old cast). But the difference is likely to be insignificant if you're only ever passing in integers. As always, if performance really matters, measure.

    Probably a more important consideration than perf is the desired behaviour. E.g. if someone passes in the string "1", do you want it to work as if they'd passed in the integer 1? If so, go for Option 1. If you want it to fail in this case, go for Option 2.