Question

What's the overhead of calling a method in .NET which returns immediately (because a condition which is the first code inside is not met)?

I'd argue that no matter how real-time your application is, that overhead is negligible and that in any case profiling should show the facts, readability being more important, but some co-workers do not agree with me and say that you should always avoid those calls...

Any other opinion?

Was it helpful?

Solution

I dare say there are some edge cases where it could be significant - but they'll be vanishingly rare. I agree with you: write for readability first.

Note that if the method is extremely short, the JIT compiler may inline it - but if it's a large method which you just happen to exit from quickly, it probably won't. In extreme cases, you may want to split the method in two: one short method (which can be inlined) to test whether the rest of the method is valid, and one to actually do the work. You could then perform the test first, then call the second method. Frankly I don't like it much, and would only suggest doing it after you'd discovered that this really was a problem... but at least you have a proposal for your colleagues for the eventuality where it really has been shown to be a problem :)

One thing you may want to think about as a reason to avoid method calls is if evaluating the arguments takes a long time. For example, consider logging:

Log.Info("I did something: {0}", action.GenerateDescription());

Now if GenerateDescription takes a long time, you don't want to execute it if logging isn't going to happen anyway... so you could write:

if (Log.IsEnabled(LogLevel.Info))
{
    Log.Info("I did something: {0}", action.GenerateDescription());
}

Another alternative is to use a delegate to defer evaluation - although this may have its own (small) cost:

Log.Info("I did something: {0}", () => action.GenerateDescription());

or using a method gruop conversion:

Log.Info("I did something: {0}", action.GenerateDescription);

That may well not be the problem your colleagues are worrying about, but it's worth thinking about :)

OTHER TIPS

It depends on how your method looks like, but the compiler might 'inline' such methods as well. Hence, there is probably no overhead at all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top