0

Should I use an easy readable code like this

if (var.isServicePGM() || var.isStandardPGM())
{
    //Much code

    if (var.isServicePGM())
    {
        //Some code
    }
    else if (var.isStandardPGM())
    {
        //Some code
    }
}

or should i use an faster code like this

if (var.isServicePGM() || var.isStandardPGM())
{
    //Much code

    if (var.isServicePGM())
    {
        //Some code
    }
    else
    {
        //Some code
    }
}

3 Answers3

5

Not sure how the second code can be faster, only in some cases and only if isStandardPGM() does some hefty calculations. You probably should assign the results to a variable and use those.

bool isService = var.isServicePGM();
bool isStandard = var.isStandardPGM();
if (isService || isStandard)
{
    //Much code
    if (isService)
    {
        //Some code
    }
    else if (isStandard)
    {
        //Some code
    }
}
5gon12eder
  • 7,236
2

Premature optimization is evil.

Unless you are absolutely sure that this method is causing a bottleneck and this is already causing issues, you should always focus on readability (and writing bug-free code) first. Highly optimized code tends to be harder to extend and debug in a future.

So, the answer is - yes, you should use more functions to increase readability.

Take a look at this StackOverflow question and answers: https://stackoverflow.com/questions/385506/when-is-optimisation-premature

Mac70
  • 356
0
  1. Do not worry about efficiency until you know it's a problem, and you can only tell that when the code is running, not before.

  2. Do worry about maintainability, which is very different from readability. Maintainability is about minimizing the opportunity for people to put in errors when they make changes to the code (for which DRY is a good principle). Readability begs the question - who is reading? Chimpanzees are intelligent, but you'll never make it readable to them. And you can make code appear to be readable just by shoving most of it off the screen with whitespace.

Mike Dunlavey
  • 12,905