Non conditional boolean to int conversion java - micro optimisation [duplicate] - java

This question already has answers here:
Converting Boolean to Integer in Java without If-Statements
(12 answers)
Closed 8 years ago.
I'm fairly new to Java and I'm writing an android game - and there's one line of code in a tight loop that's really annoying me.
targetBlocksRemain += letterArray[column][row].isTargetBlock() ? 1 : 0;
I feel like must be possible to write this without the conditional statement and therefore without the potential branch prediction performance hit.
I'll optimise out the tight loop eventually so I'm not massively concerned in the long run, but it'd be nice to know if there's a way to resolve similar situations.
edit
Just to clarify - this is a pseudo theoretical questions - there are lots of other things I could do to improve this, such as store isTargetBlock as an int. I'm not really interested in other suggestions, just wondering if there's a way do resolve this particular issue.
edit 2
Hoping to look at what the Dalvik VM is doing shortly to work out how it handles this.

I know it might not look good but will avoid conditional statement:
do this once in the activity:
HashMap<Boolean, Integer> map=new HashMap<Boolean, Integer>();
map.put(false, 0);
map.put(true, 1);
and in loop
targetBlocksRemain += map.get(letterArray[column][row].isTargetBlock());

Related

Performance and variables [duplicate]

This question already has answers here:
Java performance vs. code-style: Making multiple method calls from the same line of code
(7 answers)
Calling getters on an object vs. storing it as a local variable (memory footprint, performance)
(6 answers)
Closed 5 years ago.
I had a performance issue when I was thinking about changing the style of the code. Previously, I liked everything to minimize, for it seemed like something to increase performance.
Example 1
new Run(path).start();
From the point of view of refactoring, it is better to write so:
Run run = new Run(path);
run.start();
So it's easier to read the code, but the question is, will I lose something because of this? Because the run is placed in the RAM?
Example 2
The line from my project (yes, creepy):
tabPane.getTabs().get(i).setUserData(Paths.get(newFile.substring(0, indexOfDifference) + name + path.toString().substring(indexOfDifference + nameOfDifference.length(), path.toString().length())));
It is difficult to read this code to a person, I understand, but if I sign every step:
String firstHalf = newFile.substring(0, indexOfDifference);
String secondHalf = path.toString().substring(indexOfDifference + nameOfDifference.length());
Path path = Paths.get(firstHalf + name + secondHalf);
tabPane.getTabs().get(i).setUserData(path);
Will I lose significant performance?
P.S. Sorry if the topic was repeated, but did not know how to write a search query.

At what point does writing, maintaining and most importantly the overhead of a function become a viable alternative to repeated code? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I've been wondering this for a while, and thought I'd pose the question today.
Example code:
private void createLinks(int numUsers) {
for (int i = 1; i <= numUsers; i++) {
String userId = "ID-" + i;
String randomId;
// Generate an ID to link to.
do {
randomId = "ID-" + random.nextInt(i);
} while (randomId.equals(iUserId));
link(userId, randomId); //links the first argument to the second,
//links are not bi-directional.
// Generate 4 more ID's to link to.
for (int j = 1; j <= 4; j++) {
do {
randomId = "ID-" + random.nextInt(i);
} while (randomId.equals(iUserId));
link(userId, randomId);
link(randomId, userId);
}
// Generate another ID to link
do {
randomId = "ID-" + random.nextInt(i);
} while (randomId.equals(iUserId));
link(randomId, userId)
}
}
#createLinks is invoked a lot, and the do...while code snippet is being repeated in the method. Does it make sense to extract these 3 lines of code out to a method called generateRandomId(int i) and incur the function overhead to avoid this repetition? If createLinks gets invoked a 100 times, generateRandomId would get invoked 100*6 = 600 times.
This is more a language agnostic question rather than one specific to java, but it'd be interesting to know if some languages handle function overhead better than others. E.g. JVM does function inlining to optimize function calls, which might mean that a developer need not wonder about things that I mentioned above.
This is definitely opinion-based question, and I expect it will be closed. But I'll try to answer it anyway, because it's quite frequently asked.
If you want simple answer – don't bother about it. It's probably too soon. Really, the manner you ask a question tells me that you have a lack of information about how frequently this code will be called and how slow it really is. And it's ok. We all face this situation when there are just a lot of unknowns in the context of development. The trick is – those unknown will become knowns in operation context (when your code is actually running). You'll get a feedback about performance issues if any. It should be said, getting this feedback is not so simple task by itself and requires some skills and mature toolchain. But it's not the question you asked.
Does I advocate skip any performance optimization while developing? Of course no, it's silly. There are issues which could and should be solved early. I'm just advising to follow simple and straightforward principle:
If you're in doubt – wait for reality to show you the right way.
This principle could be misused as any other. But I hope you get my point – premature optimization is the root of all evil, right?
My opinionated answer is "always." Whenever I find myself writing the same code twice, I make it a function.
The point where this practice ceases to be opinion-based is when two pieces of code doing exactly the same thing is important to the proper operation of the program.

Data types usage in java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am not new in java but when I write program I always use int Type of my variables. I want to know when I need to use int data, when byte, when long and so on... Can U explain me this with examples please.
If you are asking when to use float, double and long etc. This document can help you to understand.
For example, int is 32 bit but long is 64 bit. If you need to set a value over 32 bit you should use long to store data.
Good luck.
It basically depends on how you wanna use them and what considerations would you have (size, data type,..etc). I would recommend going throw Oracle's docs.
The types used should be the product of a deep thought about various of things, including (but not limited to) int over long (32bit vs 64bit), char over byte (user friendliness vs performance) , complex data structures over simple ones (Performance), backwards compatibility (JRE version), platforms the program's gonna run on (Windows? Unix? Mac OS?), readability of the code (Sometimes writing "byte x = 0xFF; char ch = (char)x; is worse than char ch = 'a' and the list goes on... of course some of the stuff I mentioned fit into more than one category.
This usually comes with experience. The more you code, the more platforms you want to support, the faster you want your program to respond etc...
You should always have a plan regarding your program:
What platforms will I support?
Is the task more important than performance?
...
...
I'm not saying you should carefully consider every type you choose, I'm saying you should always make the effort to tick all the V's and be satisfied about it, accomplishing everything you wanted.

if(isTesting==false) ? if(false==isTesting) ? if(!isTesting) ? which is the best way of programming [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Few years back I was writing code for conditional check as like below
boolean isTesting ==false;
if(isTesting==false)
And one fine day one of senior guy came to me and told me this is not efficient way to do. And then explained something about this to me. I heard But I guess didn’t listened.
So I started to write like as below without knowing the purpose of it.
if(false==isTesting)
Now sudden curiosity came on this subject again is really efficient!? which one is best way to do so?
if(isTesting==false) ?
if(false==isTesting) ?
if(!isTesting) ?
And same doubt about if(null==value) and if(value==null). Please clarify
Thanks in advance.
if (isTesting == false)
is a bit dangerous, because you could forget an = sign and write
if (isTesting = false)
which compiles (it assigns false to isTesting, and evaluates to false).
if (false == isTesting)
avoids the problem because forgetting an = would make the code invalid. But it's much too verbose, and compares what is already a boolean to another boolean, to produce a boolean. So
if (!isTesting)
does the same thing, shows that you understand what a booelan expression is, and doesn't have the risk of forgetting an =. You should of course prefer this last way.
Writing
if (null == value)
is unnecessary, because forgetting an equal in
if (value = null)
would cause the code to become invalid. value = null is not a boolean expession (unless value is of type Boolean). So use value == null, which is more natural.
Anyway, unless you frequently switch to a language that uses = instead of == for comparisons, you normally won't forget to use == instead of =. It becomes natural after a few days. Good IDEs and code quality tools warn you when you use = instead of == in a boolean expression.
The best of these is if (!isTesting) as it's simplest and cleanest.
Of the other two options if (value==null) is
more natural so I would recommend using that one.
Functionally they are all equivalent.
That said, the recommendation to write the constant / literal on the left side of the == is motivated by the impossibility to accidentially write = (assignment) instead of == (equality). Since you can't assign to a constant / literal the compiler would complain if you accidentially wrote =.
The short, concise !expression has no such problems, and it furthermore makes it totally obvious that expression must evaluate to a boolean (everything else would be a compile error). So a simple if (boolean) / if (!boolean) is commonly considered the most logical idiom.

Unfamiliar piece of enhanced for loop syntax [duplicate]

This question already has answers here:
"loop:" in Java code. What is this, and why does it compile?
(12 answers)
Closed 9 years ago.
I have the job of going through another's code and I'm trying to figure it all out when I came across this for loop.
//I don't understand the purpose of assetLoop
assetLoop: for (AssetObject asset : assets) {
//Some code
}
I've never seen this syntax and I can't find any reference to it anywhere through my google searches. Can anyone tell me what assetLoop: is doing? Or simply give me the name of this concept so I can do some non-mindless googling and read about it? :)
This is called a label.
It allows you to write break assetLoop from a nested loop to break out of the outer loop.
It's essentially a limited form of goto, and is rarely used.
It's a label. You can put them on any statement. break assetLoop; will break out of that loop, even if the break statement is within another for, while, do-while or switch statement. Similarly continure assetLoop; will jump to the next iteration of the loop.

Categories