Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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...

like image 829
JL. Avatar asked Dec 11 '09 22:12

JL.


People also ask

Why invert if statement?

INVERT IF STATEMENTS and EARLY RETURNS to improve your code readability. Inverting if statements and early returns are two techniques that can be applied that can improve your codebase. When used properly it can reduce indentation and complexity.

How do you reverse an IF condition?

Place your cursor in an if or if else statement. Press Ctrl+. to trigger the Quick Actions and Refactorings menu. Select Invert if.

How do you reverse an if statement in Python?

Position the caret over an if-else statement. Press Alt+Enter. From the pop-up menu, select Invert if-else statement.


1 Answers

It doesn't matter. Stop agonizing over performance issues that don't exist - use a profiler to identify areas in your code that DO exhibit issues, and fix them. Proactive optimization - before you know that there is a problem - is by definition a waste of time.

like image 172
Alex Weinstein Avatar answered Oct 07 '22 16:10

Alex Weinstein