Optimizing the use of variables for values ​​that are used only once

I often come across this doubt and I could use some opinions about it. I often use variables for values ​​that are only used once, and I'm not sure if there is a right or wrong way to do this. Is there any agreement on this?

Simple example:

int matches = 10;
int victories = 4;
int defeats = 3;

int ties = (matches - (victories + defeats));
int score = (victories*3 + ties);

      

Does it have to ties

be removed for it to become that way?

int matches = 10;
int victories = 4;
int defeats = 3;

int score = (victories*3 + (matches - (victories + defeats)));

      

Despite the silly example, I wondered about this in situations of varying complexity.

I see some pros and cons of using ties

:

Pros:

  • Improves readability.
  • ties

    can be used later if needed
  • Simple maintenance

Minuses:

  • Less compact code
  • Uses more variables
  • Using resources unnecessarily

This may just be a situation of personal taste, but let me know how you handle this and why. Thank!

+3


source to share


2 answers


I recommend the first version. Since we work as teams most of the time, it would be better if the code were more readable and less cumbersome. The memory optimizations that the second version is targeting won't help) as the JVM is already doing a very good deal of freeing memory for us. If it is a local variable: JVM releases all variables (local variables) in LIFO mode (wrt call stack) If it is a member variable: JVM will garbage collect all objects (which also consist of member variables) stored on the heap on a regular basis.



+1


source


I recommend that you use whatever version is easiest to read. Between the compiler and the JIT, you are doing micro-optimizations that will not give a measurable performance difference in real-world applications.



+8


source







All Articles