I've seen this question asked many times, but in different ways and the answer has never been what I've been looking for. I'm sure I could do some tests, but I feel like this could be a good resource for others and maybe get some opinions on the matter.
Here's the issue: I have a class that implements a configuration interface. Each method that is inherited usually has a variable in it. the most common would be generic Objects.
If these methods are called over and over again, would it be more efficient to create temporary class level variables that are just overwritten every time a method is called, or create a new variable every time?
Especially during a loop. I usually try to keep all my variables local, but a programmer I was working with recently did the opposite and changed some of my code because it could be more easily changed in the future if I needed to make modifications.
If this is confusing, here's an example of what I mean:
// Reused Local Variable
private Object tempObject;
public char getChar(String key) {
tempObject = get(key); /* method that grabs and object from a map */
// more code...
}
// Recreated Local Variable
public char getChar(String key) {
Object tempObject = get(key);
// more code...
}
Please don't mark this as a duplicate question. There are many of this question around, but they all have different responses that vary drastically.
And I did my research, so don't say I didn't. (Seems to be a huge problem on this site. You can't get any help anymore because people are so quick to flag posts without even reading them just because they're similar to other posts).
These answers: here, state that if you want to reformat your code, you will be making a lot more work for yourself for no reason. And that depending on the compiler it may automatically refactor the code to the best usages. But if there's multiple users compiling the code on different compilers, one build could be much more.
These answers: here, seem to talk about just reusing a variable in a single method. Or reusing a variable for different values or types of values. If the value does something different than the first value, it should get its own name. Unless the naming of said variable is universal and can be used for different things. Integer 'i' would probably not be the best to reuse because it is so common and could be used somewhere else that could cause a conflict. Something like 'score' could be reused as long as the value that you're putting into it is related and compatible.