‘Stupid’ Question 21: Is there a performance win with 'as' casting, and if so - does it matter?
This is indeed a follow up question to question nr 20, ‘Stupid’ Question 20: How should I do casting in C#? Should I use the prefix cast or the as-cast?. As always one question sparks another one (or often several questions) - and this is the whole point for asking. With asking one question you will find all the other questions, and while you seek and find answer I hope it will spark that childlike curiosity we all had one day.
Is there a performance win with ‘as’ casting, and if so - does it matter?
So. Back to the question. Is ‘as’ faster than the (cast)? And if so, does it really matter today? The CLR and the computer hardware should fix that, right?
Turns out, that there is a performance win. ‘As’ checks to see if the object is of that type, and if not returns null and there is no exception. Exceptions carry a performance cost (but you might have another problem if you throw many exception), so ‘as’ will be slightly faster overall.
Does it matter?
I got the reply that it depends on how many iterations you would be doing, and if the answer to was ‘a lot’ then yes, it *could* matter, but the again also the discussion on exceptions and performance and what the real problem is.
Am I right here? This is such an interesting discussion, and I am so happy that so many devs joined in on the discussion!- keep it up guys and girls! Yey us!
Last modified on 2012-08-12