Static Fields
Suppose we have a calculation that calls the Math.cos() a lot, but does it many
times with the same argument. If the cos() funtion is time consuming,
We might do something like this to optimize our code.
CosCache.java |
1 | public class CosCache { |
2 | static double PI = 4.0*Math.acos(1.0/Math.sqrt(2.0)); |
3 | static double lastCosArg = 0.0; |
4 | static double lastCosValue = 1.0; |
5 | |
6 | static double cos(double arg) { |
7 | if(arg != lastCosArg) { |
8 | lastCosArg = arg; |
9 | lastCosValue = Math.cos(lastCosArg); |
10 | } |
11 | return lastCosValue; |
12 | } |
13 | |
14 | public static void main(String[] args) { |
15 | PI = 3.14; // make sure PI is set! |
16 | double sum = 0; |
17 | for(int i=0;i<10;i++) { |
18 | if(i == 74) { |
19 | sum += cos(.7*PI); |
20 | } else { |
21 | sum += cos(.3*PI); |
22 | } |
23 | } |
24 | System.out.println("sum="+sum); |
25 | } |
26 | } |
$ javac CosCache.java
| $ java CosCache
sum=5.88171730331375
|
Here we've introduced three static fields.
- PI - This is supposed to hold the numerical value of pi.
- lastCosArg - This holds the last value we passed to the cos() function.
- lastCosValue - This is always equal to Math.cos(lastCosArg)
There is, of course, a small bug in this program. When we initialized we supplied a highly
accurate value of PI by using 4.0*Math.acos(1/Math.sqrt(2.0)) (Note: acos() is the arc cosine).
One can prevent this sort of bug by making PI final. Final means that the value of PI cannot
be changed.
CosCache2.java |
1 | public class CosCache2 { |
2 | final static double PI = 4.0*Math.acos(1.0/Math.sqrt(2.0)); |
3 | static double lastCosArg = 0.0; |
4 | static double lastCosValue = 1.0; |
5 | |
6 | static double cos(double arg) { |
7 | if(arg != lastCosArg) { |
8 | lastCosArg = arg; |
9 | lastCosValue = Math.cos(lastCosArg); |
10 | } |
11 | return lastCosValue; |
12 | } |
13 | |
14 | public static void main(String[] args) { |
15 | PI = 3.14; // make sure PI is set! |
16 | double sum = 0; |
17 | for(int i=0;i<10;i++) { |
18 | if(i == 74) { |
19 | sum += cos(.7*PI); |
20 | } else { |
21 | sum += cos(.3*PI); |
22 | } |
23 | } |
24 | System.out.println("sum="+sum); |
25 | } |
26 | } |
$ javac CosCache2.java
CosCache2.java:15: cannot assign a value to final variable PI
PI = 3.14; // make sure PI is set!
^
1 error
|
|