Do out parameters in C# have any performance implications I should know about? (Like exceptions)
I mean, is it a good idea to have a method with an out parameter in a loop that will run a couple of million times a second?
I know it’s ugly but I am using it the same way as Int32.TryParse is using them – returning a bool to tell if some validation was successful and having an out parameter containing some additional data if it was successful.
I doubt that you’ll find any significant performance penalty to using an
outparameter. You’ve got to get information back to the caller somehow or other –outis just a different way of doing it. You may find there’s some penalty if you use the out parameter extensively within the method, as it may well mean an extra level of redirection for each access. However, I wouldn’t expect it to be significant. As normal, write the most readable code and test whether performance is already good enough before trying to optimise further.EDIT: The rest of this is an aside, effectively. It’s only really relevant for large value types, which should usually be avoided anyway 🙂
I disagree with Konrad’s assertion about ‘return values for all types > 32 bit are handled similar or identical to out arguments on the machine level anyway’ though. Here’s a little test app:
Results:
Basically by using an out parameter we’re writing the data directly to the final destination, rather than writing it to the small method’s stack frame and then copying it back into the Main method’s stack frame.
Feel free to criticise the benchmark app though – I may have missed something!