Returning when a codition is not met vs. doing stuff when the condition is met

hey, I’m making a game and I got to this situation where I only want to do something if the .collider of a RaycastHit is not null, so I used an if statement that returns when the collider is null.
but now it got me thinking, is there any performance difference between using return when a condition is not met and doing something inside an if when the conditions are met? if not, would any of those cases be better on a clean code perspective?

example in code:

if (ray.collider == null) { return; }
// do stuff

// or
 
if (ray.collider != null) {
    //do stuff
}

There is no performance difference, there is only a code style difference. And that difference is largely subjective. I’ve seen video where people argue that “using return as often as possible” is the best style, I’ve seen people who staunchly refuse to return before the end of a method. Most of us end up somewhere in between.

3 Likes

Using an early return is (at least sometimes) called a “guard clause.” For example:

private void DoSomething()
{
    if (myVariable == 0)
        return;

    anotherVariable++;
    PerformLogic();
    FinishUp();
}

These can help reduce nesting, in situations where deep nesting would otherwise be an issue. They also look nice, in my opinion. But as with so many techniques, they’re not the only way to write clean code, and they’re not the best choice in every single situation.

1 Like