Jtest logo




Contents  Previous  Next  Index

OPT.USV


Use `stack' variables whenever possible

Description

This rule flags any non-stack variable that is going to be accessed frequently.

When variables are accessed frequently, consider where these variables are accessed from. Is the variable static, local, or an instance variable? It is about two to three times slower to access "static", instance variables than to access stack variables.

Example

 package OPT;
 public class USV {
     void getSum (int[] values) {
         for (int i=0; i < value.length; i++) {
             _sum += value[i];           // violation.
         }
     }
     void getSum2 (int[] values) {
         for (int i=0; i < value.length; i++) {
             _staticSum += value[i];
         }
     }
     private int _sum;
     private static int _staticSum;
 }

Repair

Use stack variables whenever possible if variables are going to be accessed frequently.

You can replace the above "getSum()" method in the following way:

 void getSum (int[] values) {
     int sum = _sum;  // temporary stack variable.
     for (int i=0; i < value.length; i++) {
         sum += value[i];
     }
     _sum = sum;
 }

Reference

Haggar, Peter. Practical Java - Programming Language Guide. Addison Wesley, 2000, pp.122 - 125.


Contents  Previous  Next  Index

ParaSoft logo
(888) 305-0041 info@parasoft.com Copyright © 1996-2001 ParaSoft