JonHerbert
JonHerbert

Reputation: 677

Does it make a difference when I return the value from a method?

This is my code currently - I'm just iterating through some lists and returning strings.

public string CreateCharacterName (int category) {
    string name = "";

    if(category == 0) {
        int r = Random.Range(0, Names(Roots("Characters", "CharacterNames"), 0).Count);
        name = Names(Roots("Characters", "CharacterNames"), 0)[r];
    }

    return name;
}

I've cut out a bunch of similar if statements, but I'm wondering if I should put the 'return name' part into each of the if statements after I've got the result, or is it fine as it is? Both work, I'm just thinking that the method will continue checking each subsequent if statement against the 'category' and THEN return the string, is that correct and is there a cost to that?

Thanks!

Upvotes: 1

Views: 71

Answers (2)

Barracoder
Barracoder

Reputation: 3764

It's fine as it is. Your cyclomatic complexity is 2, i.e there is only 1 binary path through your code, which is good. Moving the return name; statement would increase it a little, which isn't bad though. As a rule of thumb, try to reduce complexity.

Upvotes: 1

Rob
Rob

Reputation: 464

if microsecond optimisation is important why not skip using the variable and just use:

return Names(Roots("Characters", "CharacterNames"), 0)[r];

Upvotes: 0

Related Questions