Dimebag
Dimebag

Reputation: 843

Assign operation result to a constant

I am trying to make minor modifications to improve performance in my program. In particular, at constants. I have constants for: WIDTH = x, HEIGHT = y and AREA = x*y.

Now, how does java proceed when using the constant AREA?

Does it calculate every time the result of x * y and use it where it's needed? Or does it calculate x*y once, in the beginning, and store the result under the "variable" AREA?

In other words, assume WIDTH = 10, HEIGHT = 20; is it better to do the calculation yourself and assign AREA = 200? Or just write AREA = WIDTH*HEIGHT? Also assume you would need this constant many times in the program.

In my case, I don't think it matters much in terms of performance/efficiency, but I imagine in large programs it would.

Thanks!

EDIT: To make it clear what I mean with "constants":

e.g.

final static int WIDTH = 10, 
    HEIGHT = 20, 
    AREA = HEIGHT*WIDTH;

Upvotes: 1

Views: 72

Answers (1)

Stephen C
Stephen C

Reputation: 719346

Assuming that you mean this:

 public class Test {
     final static int WIDTH = 10, HEIGHT = 20, AREA = HEIGHT * WIDTH;
 }

then all three of those constants are compile-time constants. On the other hand, in

 public class Test {
     static int WIDTH = 10, HEIGHT = 20, AREA = HEIGHT * WIDTH;
 }

the variables are not constant, but the expressions are still only evaluated once ... when the Test class is initialized.

The only cases where the expressions are going to be executed multiple times are case like this:

 public class Test {
     final int WIDTH = 10, HEIGHT = 20, AREA = HEIGHT * WIDTH;  // non-static field
 }

or this:

 public class Test {
     public void method() {
         final int WIDTH = 10, HEIGHT = 20, AREA = HEIGHT * WIDTH; // local variable
     }
 }

But in all cases, the expression will only be evaluated at runtime once (if at all) each time the declaration is evaluated. It doesn't get evaluated when (for example) you use the constant or variable.


You said:

In my case, I don't think it matters much in terms of performance/efficiency, but I imagine in large programs it would.

In the cases with statics, the difference is going to be too small to be relevant, compared with (just) the rest of the program startup overheads.

It might be relevant in the non-static cases, but probably not. It depends how often the expressions get evaluated, relative to all the other things that the application is doing.


Advice: trying to optimize code at this level is usually a waste of time ... unless 1) you have measured the application performance and determined that it is really an issue and 2) you have profiled the application and determined that the code section you are considering is really a performance bottleneck.

Upvotes: 3

Related Questions