views:

70

answers:

2

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:

  • Option 1: No casting but is maybe not so proper, does it cost less performance?
  • Option 2: Casting when the type is known, but feels more safe.

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.

+2  A: 

What you are doing in the first option is an implicit cast. The compiler creates an explicit cast for you, so what you actually get is still something similar to:

Dim x As Integer = DirectCast(obj, Integer)

You can only do an implicit cast from Object to Integer when strict mode is off. You should turn strict mode on, so that you are sure that you don't do any implicit casting by mistake. When you have turned strict mode on, you will have to do the explicit cast for the code to compile.

Guffa
The non-strict implicit cast is not quite the same as DirectCast -- it does VB6-style Evil Type Coercion.
itowlson
@itowlson: Good point. I changed the text so that it doesn't imply an exact equivalence.
Guffa
+1  A: 

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.

itowlson
And don't forget that I tagged my qestion 'implicit', an (off the record) VB will not fail even you do Dim x As Integer = "5", that's the cool (or for other people - the not cool) thing about VB.
Shimmy