use if or set value in java and kotlin - java

I need to compare these 2 codes for CPU and RAM usage. who is better?
enableValidation is a Boolean variable and need to set false.
I have 2 ways:
1. use if
2. set false direct
which one is better?
way 1:
if (enableValidation) {
enableValidation = false;
}
way 2:
enableValidation = false;

As far as CPU/RAM usage, there is almost no difference between these two mentioned code approaches. While approach one is checking for a redundant condition. Both code means at this point enableValidation has to be false, no matter what is the situation.
So code readability perspective, better to assign it to false directly.

java and kotlin will be translated to byte codes so you can view byte code and detect wich one is larger code than other
as i know from c++ , the way 2 is better but here the resource usage is about nothing !
dont realy care about it

Related

Is there any difference in optimization between integer and string comparison?

I'm trying to make a game and I have a Selection class that holds a string named str in it. I apply the following code to my selection objects every 17 milliseconds.
if(s.Str == "Upgrade") {
}else if(s.Str == "Siege") {
}else if(s.Str == "Recruit") {
}
In other words, these selection objects will do different jobs according to their types(upgrade,siege etc...). I am using str variable elsewhere. my question is that:
Would it be more optimized if I assign the types to an integer when I first create the objects?
if(s.type == 1) {
}else if(s.type == 2) {
}else if(s.type == 3) {
}
This would make me write extra lines of code(Since I have to separate objects by type when I first create) and make the code more difficult to understand, but would there be a difference between comparing integers rather than comparing strings?
If you compare strings >that< way, there is probably no performance difference.
However, that is the WRONG WAY to compare strings. The correct way is to use the equals(Object) method. For example.
if (s.Str.equals("Upgrade")) {
Read this:
How do I compare strings in Java?
I apply the following code to my selection objects every 17 milliseconds.
The time that it will take to test two strings for equality is probably in the order of tens of NANOseconds. So ... basically ... the difference between comparing strings or integers is irrelevant.
This illustrates why premature optimization is a bad thing. You should only optimize code when you know that it is going to be worthwhile to spend your time on it; i.e. when you know there is going to be a pay-off.
So should I optimize after I write and finish all the code? Does 'not doing premature optimization' means that?
No it doesn't exactly mean that. (Well .. not to me anyway.) What it means to me is that you shouldn't optimize until:
you have a working program whose performance you can measure,
you have determined specific (quantifiable) performance criteria,
you have a means of measuring the performance; e.g. an appropriate benchmarks involving real or realistic use-cases, and
you have good a means of identifying the actual performance hotspots.
If you try to optimize before you have the above, you are likely to optimize the wrong parts of the code for the wrong reasons, and your effort (programmer time) is likely to be spent inefficiently.
In your specific case, my gut feeling is that if you followed the recommended process you would discover1 that this String vs int (vs enum) is irrelevant to your game's observable performance2.
But if you want to be more scientific than "gut feeling", you should wait until you have 1 through 4 settled, and then measure to see if the actual performance meets your criteria. Only then should you decide whether or not to optimize.
1 - My prediction assumes that your characterization of the problem is close enough to reality. That is always a risk when people try to identify performance issues "by eye" rather than by measuring.
2 - It is relevant to other things; e.g. code readability and maintainability, but I'm not going to address those in this Answer.
The Answer by Stephen C is correct and wise. But your example code is ripe for a different solution entirely.
Enum
If you want performance, type-safety, easier-to-read code, and want to ensure valid values, use enum objects rather than mere strings or integers.
public enum Action { UPGRADE , SIEGE , RECRUIT }
You can use a switch for the various enum possible objects.
Action action = Action.SIEGE ;
…
switch ( action )
{
case UPGRADE:
doUpgradeStuff() ;
break;
case SIEGE:
doSiegeStuff() ;
break;
case RECRUIT:
doRecruitStuff() ;
break;
default:
doDefaultStuff() ;
break;
}
Using enums this way will get even better in the future. See JEP 406: Pattern Matching for switch (Preview).
See Java Tutorials by Oracle on enums. And for an example, see their tutorial using enums for month, day-of-week, and text style.
See also this Question, linked to others.
Comparing primitive numbers like Integer will be definitely faster compared to String in Java. It will give you faster performance if you are executing it every 17 milliseconds.
Yes there is difference. String is a object and int is a primitive type. when you are doing object == "string" it is matching the address. You need to use equals method to check the exact match.

Why using default trash value for string is wrong?

tl;dr;
Why using
string myVariable = "someInitialValueDifferentThanUserValue99999999999";
as default value is wrong?
explanation of situation:
I had a discussion with a colleague at my workplace.
He proposed to use some trash value as default in order to differentiate it from user value.
An easy example it would be like this:
string myVariable = "someInitialValueDifferentThanUserValue99999999999";
...
if(myVariable == "someInitialValueDifferentThanUserValue99999999999")
{
...
}
This is quite obvious and intuitive for me that this is wrong.
But I could not give a nice argument for this, beyond that:
this is not professional.
there is a slight chance that someone would input the same value.
Once I read that if you have such a situation your architecture or programming habits are wrong.
edit:
Thank you for the answers. I found a solution that satisfied me, so I share with the others:
It is good to make a bool guard value that indicates if the initialization of a specific object has been accomplished.
And based on this private bool variable I can deduce if I play with a string that is default empty value "" from my mechanism (that is during initialization) or empty value from the user.
For me, this is a more elegant way.
Optional
Optional can be used.
Returns an empty Optional instance. No value is present for this Optional.
API Note:
Though it may be tempting to do so, avoid testing if an object is empty by comparing with == against instances returned by Option.empty(). There is no guarantee that it is a singleton. Instead, use isPresent().
Ref: Optional
Custom escape sequence shared by server and client
Define default value
When the user enter's the default value, escape the user value
Use a marker character
Always define the first character as the marker character
Take decision based on this character and strip this character for any actual comparison
Define clear boundaries for the check as propagating this character across multiple abstractions can lead to code maintenance issues.
Small elaboration on "It's not professional":
It's often a bad idea, because
it wastes memory when not a constant (at least in Java - of course, unless you're working with very limited space that's negligible).
Even as constant it may introduce ambiguity once you have more classes, packages or projects ("Was it NO_INPUT, INPUT_NOT_PROVIDED, INPUT_NONE?")
usually it's a sign that there will be no standardized scope-bound Defined_Marker_Character in the Project Documentation like suggested in the other answers
it introduces ambiguity for how to deal with deciding if an input has been provided or not
In the end you will either have a lot of varying NO_INPUT constants in different classes or end up with a self-made SthUtility class that defines one constant SthUtility.NO_INPUT and a static method boolean SthUtility.isInputEmpty(...) that compares a given input against that constant, which basically is reinventing Optional. And you will be copy-pasting that one class into every of your projects.
There is really no need as you can do the following as of Java 11 which was four releases ago.
String value = "";
// true only if length == 0
if (value.isEmpty()) {
System.out.println("Value is empty");
}
String value = " ";
// true if empty or contains only white space
if (value.isBlank()) {
System.out.println("Value is blank");
}
And I prefer to limit uses of such strings that can be searched in the class file that might possibly lead to exploitation of the code.

convert from boolean to byte in java

I need to set byte value as method parameter. I have boolean variable isGenerated, that determines the logic to be executed within this method. But I can pass directly boolean as byte parameter this is not allowed and can't be cast in java. So the solution I have now looks like this:
myObj.setIsVisible(isGenerated ? (byte)1 : (byte)0);
But it seems odd for me. Maybe some better solution exists to do this?
your solution is correct.
if you like you may avoid one cast by doing it the following way:
myObj.setIsVisible((byte) (isGenerated ? 1 : 0 ));
additionally you should consider one of the following changes to your implementation:
change your method to something like setVisiblityState(byte state) if you need to consider more than 2 possible states
change your method to setIsVisible(boolean value) if your method does what it's looking like
You can use this solution. I found it on this very useful page
boolean vIn = true;
byte vOut = (byte)(vIn?1:0);
It is not odd. It is OK.
The odd is that you need to transform typed boolean value to not self explainable byte. However sometimes we have to do this when working with legacy APIs.
BTW if you want to save memory you can use 1 bit instead of byte, so you can group several boolean flags together while using bit for each boolean value. But this technique is relevant for huge amounts of data only when saving several bytes can be significant.

Is there a way to change the internal radix of Java code?

If I want to write a program that deals almost exclusively with, say, base 8 math, is there a way to change the source code or JVM to perform all calculations with this radix without having to explicitly change it on every integer reference?
For example, instead of...
private static final int RADIX = 8;
// ... then, elsewhere ...
System.out.println(Integer.toString(3 + 7, RADIX));
... I could just do ...
System.out.println(3 + 7);
... and have it print the same result of 12? Is there some environment variable or in-code setting I can apply? Or is this simply not possible?
This may seem arcane or a "why in the world would you want to do this" scenario, but if you can imagine having to perform a large number of non-trivial calculations under a different base, then you can see how it would become extremely tedious extremely fast to have to keep manually converting numbers to the appropriate radix.
No, there is no feature like that.
A number is a number no matter what base you're talking about, the radix only comes in when converting to/from strings. If you have to do this all of the time, then create some utility methods that do the work, and always call them. Alternatively, write your own Integer-like class that handles the fromString/toString bit.
public final class OctalInteger extends Number implements Comparable<OctalInteger> {
// Basically a copy of Integer.java, but changes the methods dealing with Strings
}
No.
Also, why would you want that? Imagine how many pieces of code you would break that run in the same JVM - no one coding libraries would expect the default radix to suddenly change.
Your use of a constant is the right way to go.
You can't change default radix. But you can easily write your own print and println procedures which would print integers in octal base.

What is preferred option for assignment and formatting?

Which one is recommended considering readability, memory usage, other reasons?
1.
String strSomething1 = someObject.getSomeProperties1();
strSomething1 = doSomeValidation(strSomething1);
String strSomething2 = someObject.getSomeProperties2();
strSomething2 = doSomeValidation(strSomething2);
String strSomeResult = strSomething1 + strSomething2;
someObject.setSomeProperties(strSomeResult);
2.
someObject.setSomeProperties(doSomeValidation(someObject.getSomeProperties1()) +
doSomeValidation(someObject.getSomeProperties2()));
If you would do it some other way, what would that be? Why would you do that way?
I'd go with:
String strSomething1 = someObject.getSomeProperties1();
String strSomething2 = someObject.getSomeProperties2();
// clean-up spaces
strSomething1 = removeTrailingSpaces(strSomething1);
strSomething2 = removeTrailingSpaces(strSomething2);
someObject.setSomeProperties(strSomething1 + strSomething2);
My personal preference is to organize by action, rather than sequence. I think it just reads better.
I would probably go in-between:
String strSomething1 = doSomeValidation(someObject.getSomeProperties1());
String strSomething2 = doSomeValidation(someObject.getSomeProperties2());
someObject.setSomeProperties(strSomething1 + strSomething2);
Option #2 seems like a lot to do in one line. It's readable, but takes a little effort to parse. In option #1, each line is very readable and clear in intent, but the verbosity slows me down when I'm going over it. I'd try to balance brevity and clarity as above, with each line representing a simple "sentence" of code.
I prefer the second. You can make it just as readable with a little bit of formatting, without declaring the extra intermediate references.
someObject.setSomeProperties(
doSomeValidation( someObject.getSomeProperties1() ) +
doSomeValidation( someObject.getSomeProperties2() ));
Your method names provide all the explanation needed.
Option 2 for readability. I don't see any memory concerns here if the methods only do what their names indicate. I would be vary with concatenations though. Performance definitely takes a beat with increasing string concats because of the immutability of Java Strings.
Just curious to know, did you really write your own removeTrailingSpaces() method or is it just an example ?
I try to have one operation per line. The main reason is this:
setX(getX().getY()+getA().getB())
If you have a NPE here, which method returned null? So I like to have intermediate results in some variable which I can see after the code fell into the strong arms of the debugger and without having to restart!
for me, it depends on the context and the surrounding code.
[EDIT: does not make any sense, sorry]
if it was in method like "setSomeObjectProperties()", I'd prefer variant 2 but perhaps would create a private method "getProperty(String name)" which removes the trailing spaces if removing the spaces is not an important operation
[/EDIT]
If validation the properties is an important step of your method, then I'd call the method "setValidatedProperties()" and would prefer a variant of your first suggestion:
validatedProp1 = doValidation(someObject.getSomeProperty1());
validatedProp2 = doValidation(someObject.getSomeProperty2());
someObject.setSomeProperties(validatedProp1, validatedProp2);
If validation is not something important of this method (e.g. there's no point in returning properties which are not validated), I'd try to put the validation-step in "getSomePropertyX()"
Personally, I prefer the second one. It's less cluttered and I don't have to keep track of those temporary variables.
Might change easily with more complex expressions, though.
I like both Greg and Bill versions, I think I would more naturally write code like Greg's one. One advantage with intermediary variables: it is easier to debug (in the general case).

Categories