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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With