`

(转)对象复用

 
阅读更多
public class Student {
    private String name;
    private String course;
    private double score;

    public Student(){}

    public Student(String name, String course, double score) {
this.name = name;
this.course = course;
this.score = score;
    }

    public double getScore() {
return this.score;
    }

    //计算学生总成绩
    public double totalScore(String[] names, String[] courses, double[] scores) {
int nLen = (null == names) ? 0 : names.length;
int cLen = (null == courses) ? 0 : courses.length;
int sLen = (null == scores) ? 0 : scores.length;

double total = 0;

if (nLen == cLen && cLen == sLen) {
    for (int i = 0; i < nLen; i++) {
//实例化一个学生对象
Student s = new Student(names[i], courses[i], scores[i]); //1
total += s.getScore();
    }
}

return total;
    }
}

在代码1中,我们定义了一个Student类,该类中包括了三个成员,为客户端提供了计算多位学生的总成绩功能totalScore函数。在该函数中存在一个循环语句用于遍历每位学生的成绩并进行叠加。在每次循环的时候都会创建一个Student对象,如果学生数量为N,那么就会创建N个对象,并且这些对象一旦被创建后,脱离循环后就不会被使用。我们可以想象JVM耗费了内存和时间创建出来的对象没有怎么被“发扬光大”就这样“默默无闻”的被回收了,想想都觉得很是可惜。

的确是很可惜,对于上述业务场景,我们可以采用“对象复用”技术,减少创建对象数量,提高对象利用率,进而提升程序性能,如代码2所示。

2
public class Student {
    private String name;
    private String course;
    private double score;

    public Student(){}

    public Student(String name, String course, double score) {
this.name = name;
this.course = course;
this.score = score;
    }

    public double getScore() {
return this.score;
    }
       
    //为对象的所有成员重新赋值
    public void reInit(String n,String c,double s){
this.name = n;
this.course = c;
this.score = s;
    }
   
    //计算学生总成绩
    public double totalScore(String[] names, String[] courses, double[] scores) {
int nLen = (null == names) ? 0 : names.length;
int cLen = (null == courses) ? 0 : courses.length;
int sLen = (null == scores) ? 0 : scores.length;

double total = 0;

      Student s = new Student();
if (nLen == cLen && cLen == sLen) {
    for (int i = 0; i < nLen; i++) {
//在循环体内不断的复用对象引用s而不再实例化新的学生对象
s.reInit(names[i], courses[i], scores[i]); //2
total += s.getScore();
    }
}

return total;
    }
}

如代码2所示,“对象复用”的实现方式,就是把已定义好的对象进行复用,具体复用的方式如上述代码中的reInit函数所示,需要将待复用的对象的所有或必要的成员变量进行重新初始化,这样内存空间不变、地址不变、只是内存中存放的内容发生了变化,对业务而言好像是重新变成了另外一个对象一样。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics