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.
Related
This question already has answers here:
variable access outside of if statement
(5 answers)
What is 'scope' in Java?
(2 answers)
Closed 2 years ago.
I'm new to programming and I thought it would be fun to build a game, but I've run into an issue. I want to make it to where the user can collect an item once but once they collect it they can't collect it anymore. The way I'm seeing if they collect it is by changing the value of that variable from 0 to 1. This is what I've got for the collection, but it doesn't seem to be working. It's saying it can't find the variable yesCookie. I also want to point out that this is just the section that allows you to take it or not, the variable stuff is somewhere else.
if(moldyCookie == 0)
{
String yesCookie = "In a cavity within the wall you see a mold-covered cookie. Bleh. \nYou obtained the Rotten Cookie!\n";
}
else
{
String yesCookie = "There's nothing but an empty cavity in the wall. ";
}
System.out.println("You walk forward towards the painting, moving it aside."+yesCookie+"You return to the door.");
System.out.println();
This question already has answers here:
Run piece of code contained in a String
(9 answers)
Closed 5 years ago.
I'm trying to convert a string in code in Java, but i have no idea how to do it or if it is possible.
This is my Java code (Measure is an other class I have created)
String str= "Measure m = new Measure(10,1);";
Is it possible to run the code in the string?
No I dont think that is a good practice, you don't need to do it that way,
just instantiate outside of the string, it will be fine and good practice.
Measure m = new Measure(10,1);
This question already has answers here:
How do I determine whether an array contains a particular value in Java?
(30 answers)
Closed 7 years ago.
I am doing a "Rock,Paper,Scissors" game with Java and I have a question, is there any way to create and Array with answers and check if any of these values equal to another array? For example:
Here is the answerArray (also I want to have short cuts for answers):
String[] answersArray = {"Rock","R","Paper","P","Scissors","S"};
And here is a randomArray for computer:
String[] npcAnswer = {"Rock","Paper","Scissors"};
int idx = new Random().nextInt(npcAnswer.length);
String npcRandomAnswer = (npcAnswer[idx]);
So, I want to check through the scanner if my answer (answersArray) equal to npcRandomAnswer.
Sorry if I have grammar mistakes, I did my best to explain my point.
Thank you.
You can only compare apples with apples. Or actually you can compare apples with oranges, but then you don't really need to compare them, you know the answer will always be false.
It looks like you don't really know yet what will your algorithm be.
I suggest you to concentrate on the algorithm, write pseudo code, and when you have it, try to make java out of it. If you'll have problem with the java, we can easily help you if you post your algorithm (in a new question)
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.
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());