JL. JL. - 1 year ago 44
C# Question

Why does ReSharper invert IFs for C# code? Does it give better performance (even slightly)?

Consider the following code sample:

private void AddEnvelope(MailMessage mail)
{
if (this.CopyEnvelope)
{
// Perform a few operations
}
}


vs

private void AddEnvelope(MailMessage mail)
{
if (!this.CopyEnvelope) return;
// Perform a few operations
}


Will the bottom code execute any faster? Why would ReSharper make this recommendation?

Update

Having thought about this question the answer might seem obvious to some. But lots of us developers were never in the habit of nesting zounds of
if
statements in the first place...

Answer Source

Updated Answer:

It's a code maintainability suggestion. Easier to read than nesting the rest of the code in an IF statement. Examples/discussion of this can be seen at the following links:

Original Answer:

It will actually run (very negligibly) slower from having to perform a NOT operation.

So much in fact, some people actually consider that prettier way to code as it avoids an extra level of indentation for the bulk of the code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download