title:JAVA程序性能调优笔记(3)-有助于改善性能的技巧
tags: 有助于改善性能的技巧
grammar_cjkRuby: true
1.慎用异常
@Test
public void testInForTryCatch() {//性能差
long starttime=System.currentTimeMillis();
int a=0;
for(int i=0;i<100000000;i++){
try{
a++;
}catch(Exception e){
}
}
long endtime=System.currentTimeMillis();
System.out.println("testInForTryCatch:"+(endtime-starttime));
}
@Test
public void testOutForTryCatch() {//性能好
long starttime=System.currentTimeMillis();
int a=0;
try{
for(int i=0;i<100000000;i++){
a++;
}
}catch(Exception e){
}
long endtime=System.currentTimeMillis();
System.out.println("testOutForTryCatch:"+(endtime-starttime));
}
2.使用局部变量
局部变量的访问速度远远高于类的成员变量
@Test
public void testLocalVar() {
long starttime=System.currentTimeMillis();
int a=0;
for(int i=0;i<100000000;i++){
a++;
}
long endtime=System.currentTimeMillis();
System.out.println("testLocalVar:"+(endtime-starttime));
}
@Test
privat static int ta = 0;
public void testMemberVar() {
long starttime=System.currentTimeMillis();
for(int i=0;i<100000000;i++){
ta++;
}
long endtime=System.currentTimeMillis();
System.out.println("testMemberVar:"+(endtime-starttime));
}
3.位运算代替乘除法
老生常谈,能搞这个的人不多。
位运算的常见操作和题目
一种经典位运算的规则
4.替换switch(jdk1.7以上版本switch性能以纠正)
5.一维数组代替二维数组
如果将 array.length 提出来,特别是对二维数组则有很好的优化效果。
6.提取表达式
@Test
public void testWeitiqu(){
double d=Math.random();
double a=Math.random();
double b=Math.random();
double e=Math.random();
double x,y;
long starttime=System.currentTimeMillis();
for(int i=0;i<10000000;i++){
x=d*a*b/3*4*a;
y=e*a*b/3*4*a;//重复应该抽象
}
long endtime=System.currentTimeMillis();
System.out.println("testWeitiqu:"+(endtime-starttime));
}
@Test
public void testTiqu(){
double d=Math.random();
double a=Math.random();
double b=Math.random();
double e=Math.random();
double t,x,y;
long starttime=System.currentTimeMillis();
for(int i=0;i<10000000;i++){
t=a*b/3*4*a;
x=d*t; //抽象后 速度有很高提升
y=e*t;
}
long endtime=System.currentTimeMillis();
System.out.println("testTiqu:"+(endtime-starttime));
}
7.展开循环
顾名思义,通过方法减少循环次数,有效的降低时间。
8.布尔运算代替位运算
我们很少用位运算,所以了解一下即可。
9.使用arrayCopy()
@Test
public void testArrayCopySystem(){
int size=100000;
int[] array=new int[size];
int[] arraydst=new int[size];
for(int i=0;i<array.length;i++){
array[i]=i;
}
long starttime=System.currentTimeMillis();
for(int k=0;k<1000;k++)
System.arraycopy(array, 0, arraydst, 0, size);
long endtime=System.currentTimeMillis();
System.out.println("testArrayCopySystem:"+(endtime-starttime)+" last:"+arraydst[size-1]);
}
10.使用clone()代替 new
使用在大对象上面,小对象用new足可以了。可以参考一下Java克隆技术
11.静态方法代替实例方法
静态方法明显快与实例方法。