Java程序性能优化总结

1.避免在循环条件中使用复杂表达式

在不做编译优化的情况下,在循环中,循环条件会被反复计算,如果不使用复杂表达式,而使循
环条件值不变的话,程序将会运行的更快。
例子:

1 import java.util.vector;
2 class cel {
3 void method (vector vector) {
4 for (int i = 0; i < vector.size (); i++) // violation
5 ; // ...
6 }
7 }

更正:

1 class cel_fixed {
2 void method (vector vector) {
3 int size = vector.size ()
4 for (int i = 0; i < size; i++)
5 ; // ...
6 }
7 }

2.为'vectors' 和 'hashtables'定义初始大小

jvm 为 vector 扩充大小的时候需要重新创建一个更大的数组,将原原先数组中的内容复制过
来,最后,原先的数组再被回收。可见 vector 容量的扩大是一个颇费时间的事。
通常,默认的 10 个元素大小是不够的。你最好能准确的估计你所需要的最佳大小。

3.在 finally 块中关闭 stream

程序中使用到的资源应当被释放,以避免资源泄漏。这最好在 finally 块中去做。不管程序执行
的结果如何,finally 块总是会执行的,以确保资源的正确关闭。

4.使用'system.arraycopy ()'代替通过来循环复制数组

'system.arraycopy ()' 要比通过循环来复制数组快的多。

5.让访问实例内变量的 getter/setter 方法变成”final”

简单的 getter/setter 方法应该被置成 final,这会告诉编译器,这个方法不会被重载,所以,可
以变成”inlined”

6.避免不需要的 instanceof 操作

7.单个字符使用char代替String,譬如indexof,startswith()

8.使用移位操作来代替'a / b'操作

"/"是一个很“昂贵”的操作,使用移位操作将会更快更有效。
例子:

 1 public class sdiv {
 2 public static final int num = 16;
 3 public void calculate(int a) {
 4 int div = a / 4;
 5 // should be replaced with "a >> 2".
 6 int div2 = a / 8;
 7 // should be replaced with "a >> 3".
 8 int temp = a / 3;
 9 }
10 }

更正:

1 public class sdiv {
2 public static final int num = 16;
3 public void calculate(int a) {
4 int div = a >> 2;
5 int div2 = a >> 3;
6 int temp = a / 3;
7 // 不能转换成位移操作
8 }
9 }

9、使用移位操作代替'a * b'同上。

[i]但我个人认为,除非是在一个非常大的循环内,性能非常重要,而且你很清楚你自己在做什
么,方可使用这种方法。否则提高性能所带来的程序晚读性的降低将是不合算的。
例子:

1 public class smul {
2 public void calculate(int a) {
3 int mul = a * 4;
4 // should be replaced with "a << 2".
5 int mul2 = 8 * a;
6 // should be replaced with "a << 3".
7 int temp = a * 3;
8 }
9 }


更正:

1 package opt;
2 public class smul {
3 public void calculate(int a) {
4 int mul = a << 2;
5 int mul2 = a << 3;
6 int temp = a * 3;
7 // 不能转换
8 }
9 }

 

原文地址:https://www.cnblogs.com/androidstudy/p/5520773.html