views:

73

answers:

2

Hi

I'd like to know what's the overhead of calling a method- in .Net -which returns inmediatly (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, being readability more important, but some co-workers do not agree with me and say that you should always avoid those calls...

Any other opinion?

A: 

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

naivists
Note that it would be the JIT compiler, not the C# compiler.
Jon Skeet
Nice clarification, Skeet
Román
But still not clear how the JIT would inline a method which is not trivial. Maybe that's what you mean by "might" naivists?
Román
+2  A: 

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 :)

Jon Skeet
Sorry to enlarge Skeet's bloated reputation, but his answer was more complete ;-)
Román