Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you create variables for a if statement?

I was wondering, what technically would be the most efficient way.

What would be smarter to code with:

    if (args[0].toLowerCase().toString().equals("server")) {
        System.out.println("SERVER");
    }

Or:

    String host = args[0].toLowerCase();

    if (host.equals("server")) {
        System.out.println("SERVER");
    }

Keep in mind, I know that this variable is redundant. And that an argument can also contain a number, but that is not the case of my question. It's just a example.

When should you create a variable for an if statement? Always? Is it safer? Should I do it not, because I am wasting memory? Does it impact the performance at all?

like image 626
user2586851 Avatar asked Dec 05 '22 21:12

user2586851


1 Answers

By all means, create the variable. A single variable like that will never, ever be a performance bottleneck, never.

Always favor readability. Performance problems usually appear only in specifics parts of a system. When they arise, and not before measuring those (aka having numbers), you treat them case by case. Never forget: Premature optimization is the root of all evil.

In your specific case, you could go even further and create another variable, explaining the intent of the comparison:

String host = args[0].toLowerCase();
boolean isRunningUnderProduction = host.equals("server");
if (isRunningUnderProduction) {
    System.out.println("SERVER");
}

Much better than a comment. And explains the intent of the code within a glimpse.


A quote from Martin Fowler's Refactoring book:

The interesting thing about performance is that if you analyze most programs, you find that they waste most of their time in a small fraction of the code. If you optimize all the code equally, you end up with 90 percent of the optimizations wasted, because you are optimizing code that isn't run much. The time spent making the program fast, the time lost because of lack of clarity, is all wasted time.

In other words: if your programs are easier to read, they are easier to fix the slow parts, when the time comes (if it comes).

like image 189
acdcjunior Avatar answered Dec 20 '22 08:12

acdcjunior