Java性能优化

发表于:2008-11-17 14:23

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:网络转载

  十七、使用条件操作符替代"if (cond) return; else return;" 结构

  条件操作符更加的简捷 

  例子:

public class IF {
public int method(boolean isDone) {
if (isDone) {
return 0;
} else {
return 10;
}
}
}

  更正:

public class IF {
public int method(boolean isDone) {
return (isDone ? 0 : 10);
}
}

  十八、使用条件操作符代替"if (cond) a = b; else a = c;" 结构

  例子:

public class IFAS {
void method(boolean isTrue) {
if (isTrue) {
_value = 0;
} else {
_value = 1;
}
}
private int _value = 0;
}

  更正:

public class IFAS {
void method(boolean isTrue) {
_value = (isTrue ? 0 : 1); // compact expression.
}
private int _value = 0;
}

  十九、不要在循环体中实例化变量

  在循环体中实例化临时变量将会增加内存消耗

  例子:

import java.util.Vector;
public class LOOP {
void method (Vector v) {
for (int i=0;i < v.size();i++) {
Object o = new Object();
o = v.elementAt(i);
}
}
}

  更正:

  在循环体外定义变量,并反复使用

import java.util.Vector;
public class LOOP {
void method (Vector v) {
Object o;
for (int i=0;i<v.size();i++) {
o = v.elementAt(i);
}
}
}

  二十、确定 StringBuffer的容量

  StringBuffer的构造器会创建一个默认大小(通常是16)的字符数组。在使用中,如果超出这个大小,就会重新分配内存,创建一个更大的数组,并将原先的数组复制过来,再丢弃旧的数组。在大多数情况下,你可以在创建 StringBuffer的时候指定大小,这样就避免了在容量不够的时候自动增长,以提高性能。

  例子:

public class RSBC {
void method () {
StringBuffer buffer = new StringBuffer(); // violation
buffer.append ("hello");
}
}


  更正:

  为StringBuffer提供寝大小。

public class RSBC {
void method () {
StringBuffer buffer = new StringBuffer(MAX);
buffer.append ("hello");
}
private final int MAX = 100;
}

  参考资料:

Dov Bulka, "Java Performance and Scalability Volume 1: Server-Side Programming
Techniques" Addison Wesley, ISBN: 0-201-70429-3 p.30 – 31

65/6<123456>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号