1、避免在循环条件中使用复杂表达式
在不作编译优化的状况下,在循环中,循环条件会被反复计算,若是不使用复杂表达式,而使循环条件值不变的话,程序将会运行的更快。
例子: html
import java.util.vector; class cel { void method (vector vector) { for (int i = 0; i < vector.size (); i++) // violation ; // ... } }
更正: java
class cel_fixed { void method (vector vector) { int size = vector.size () for (int i = 0; i < size; i++) ; // ... } }
2、为'vectors' 和 'hashtables'定义初始大小
jvm为vector扩充大小的时候须要从新建立一个更大的数组,将原原先数组中的内容复制过来,最后,原先的数组再被回收。可见vector容量的扩大是一个颇费时间的事。
一般,默认的10个元素大小是不够的。你最好能准确的估计你所须要的最佳大小。
例子: android
import java.util.vector; public class dic { public void addobjects (object[] o) { // if length > 10, vector needs to expand for (int i = 0; i< o.length;i++) { v.add(o); // capacity before it can add more elements. } } public vector v = new vector(); // no initialcapacity. }
更正:
本身设定初始大小。 数据库
public vector v = new vector(20); public hashtable hash = new hashtable(10);
参考资料:
dov bulka, "java performance and scalability volume 1: server-side programming
techniques" addison wesley, isbn: 0-201-70429-3 pp.55 – 57
3、在finally块中关闭stream
程序中使用到的资源应当被释放,以免资源泄漏。这最好在finally块中去作。无论程序执行的结果如何,finally块老是会执行的,以确保资源的正确关闭。
例子: express
import java.io.*; public class cs { public static void main (string args[]) { cs cs = new cs (); cs.method (); } public void method () { try { fileinputstream fis = new fileinputstream ("cs.java"); int count = 0; while (fis.read () != -1) count++; system.out.println (count); fis.close (); } catch (filenotfoundexception e1) { } catch (ioexception e2) { } } }
更正:
在最后一个catch后添加一个finally块
参考资料:
peter haggar: "practical java - programming language guide".
addison wesley, 2000, pp.77-79
4、使用'system.arraycopy ()'代替经过来循环复制数组
'system.arraycopy ()' 要比经过循环来复制数组快的多。
例子: 编程
public class irb { void method () { int[] array1 = new int [100]; for (int i = 0; i < array1.length; i++) { array1 [i] = i; } int[] array2 = new int [100]; for (int i = 0; i < array2.length; i++) { array2 [i] = array1 [i]; // violation } } }
更正: api
public class irb { void method () { int[] array1 = new int [100]; for (int i = 0; i < array1.length; i++) { array1 [i] = i; } int[] array2 = new int [100]; system.arraycopy(array1, 0, array2, 0, 100); } }
参考资料:
http://www.cs.cmu.edu/~jch/java/speed.html
5、让访问实例内变量的getter/setter方法变成”final”
简单的getter/setter方法应该被置成final,这会告诉编译器,这个方法不会被重载,因此,能够变成”inlined”
例子: 数组
class maf { public void setsize (int size) { _size = size; } private int _size; }
更正: 安全
class daf_fixed { final public void setsize (int size) { _size = size; } private int _size; }
参考资料:
warren n. and bishop p. (1999), "java in practice", p. 4-5
addison-wesley, isbn 0-201-36065-9
6、避免不须要的instanceof操做
若是左边的对象的静态类型等于右边的,instanceof表达式返回永远为true。
例子: 多线程
public class uiso { public uiso () {} } class dog extends uiso { void method (dog dog, uiso u) { dog d = dog; if (d instanceof uiso) // always true. system.out.println("dog is a uiso"); uiso uiso = u; if (uiso instanceof object) // always true. system.out.println("uiso is an object"); } }
更正:
删掉不须要的instanceof操做。
class dog extends uiso { void method () { dog d; system.out.println ("dog is an uiso"); system.out.println ("uiso is an uiso"); } }
7、避免不须要的造型操做
全部的类都是直接或者间接继承自object。一样,全部的子类也都隐含的“等于”其父类。那么,由子类造型至父类的操做就是没必要要的了。
例子:
class unc { string _id = "unc"; } class dog extends unc { void method () { dog dog = new dog (); unc animal = (unc)dog; // not necessary. object o = (object)dog; // not necessary. } }
更正:
class dog extends unc { void method () { dog dog = new dog(); unc animal = dog; object o = dog; } }
参考资料:
nigel warren, philip bishop: "java in practice - design styles and idioms
for effective java". addison-wesley, 1999. pp.22-23
8、若是只是查找单个字符的话,用charat()代替startswith()
用一个字符做为参数调用startswith()也会工做的很好,但从性能角度上来看,调用用string api无疑是错误的!
例子:
public class pcts { private void method(string s) { if (s.startswith("a")) { // violation // ... } } }
更正
将'startswith()' 替换成'charat()'.
public class pcts { private void method(string s) { if ('a' == s.charat(0)) { // ... } } }
参考资料:
dov bulka, "java performance and scalability volume 1: server-side programming
techniques" addison wesley, isbn: 0-201-70429-3
9、使用移位操做来代替'a / b'操做
"/"是一个很“昂贵”的操做,使用移位操做将会更快更有效。
例子:
public class sdiv { public static final int num = 16; public void calculate(int a) { int div = a / 4; // should be replaced with "a >> 2". int div2 = a / 8; // should be replaced with "a >> 3". int temp = a / 3; } }
更正:
public class sdiv { public static final int num = 16; public void calculate(int a) { int div = a >> 2; int div2 = a >> 3; int temp = a / 3; // 不能转换成位移操做 } }
10、使用移位操做代替'a * b'
同上。
[i]但我我的认为,除非是在一个很是大的循环内,性能很是重要,并且你很清楚你本身在作什么,方可以使用这种方法。不然提升性能所带来的程序晚读性的下降将是不合算的。
例子:
public class smul { public void calculate(int a) { int mul = a * 4; // should be replaced with "a << 2". int mul2 = 8 * a; // should be replaced with "a << 3". int temp = a * 3; } }
更正:
package opt; public class smul { public void calculate(int a) { int mul = a << 2; int mul2 = a << 3; int temp = a * 3; // 不能转换 } }
11、在字符串相加的时候,使用 ' ' 代替 " ",若是该字符串只有一个字符的话
例子:
public class str { public void method(string s) { string string = s + "d" // violation. string = "abc" + "d" // violation. } }
更正:
将一个字符的字符串替换成' '
public class str { public void method(string s) { string string = s + 'd' string = "abc" + 'd' } }
12、不要在循环中调用synchronized(同步)方法
方法的同步须要消耗至关大的资料,在一个循环中调用它绝对不是一个好主意。
例子:
import java.util.vector; public class syn { public synchronized void method (object o) { } private void test () { for (int i = 0; i < vector.size(); i++) { method (vector.elementat(i)); // violation } } private vector vector = new vector (5, 5); }
更正:
不要在循环体中调用同步方法,若是必须同步的话,推荐如下方式:
import java.util.vector; public class syn { public void method (object o) { } private void test () { synchronized{//在一个同步块中执行非同步方法 for (int i = 0; i < vector.size(); i++) { method (vector.elementat(i)); } } } private vector vector = new vector (5, 5); }
十3、将try/catch块移出循环
把try/catch块放入循环体内,会极大的影响性能,若是编译jit被关闭或者你所使用的是一个不带jit的jvm,性能会将降低21%之多!
例子:
import java.io.fileinputstream; public class try { void method (fileinputstream fis) { for (int i = 0; i < size; i++) { try { // violation _sum += fis.read(); } catch (exception e) {} } } private int _sum; }
更正:
将try/catch块移出循环
void method (fileinputstream fis) { try { for (int i = 0; i < size; i++) { _sum += fis.read(); } } catch (exception e) {} }
参考资料:
peter haggar: "practical java - programming language guide".
addison wesley, 2000, pp.81 – 83
十4、对于boolean值,避免没必要要的等式判断
将一个boolean值与一个true比较是一个恒等操做(直接返回该boolean变量的值). 移走对于boolean的没必要要操做至少会带来2个好处:
1)代码执行的更快 (生成的字节码少了5个字节);
2)代码也会更加干净 。
例子:
public class ueq { boolean method (string string) { return string.endswith ("a") == true; // violation } }
更正:
class ueq_fixed { boolean method (string string) { return string.endswith ("a"); } }
十5、对于常量字符串,用'string' 代替 'stringbuffer'
常量字符串并不须要动态改变长度。
例子:
public class usc { string method () { stringbuffer s = new stringbuffer ("hello"); string t = s + "world!"; return t; } }
更正:
把stringbuffer换成string,若是肯定这个string不会再变的话,这将会减小运行开销提升性能。
十6、用'stringtokenizer' 代替 'indexof()' 和'substring()'
字符串的分析在不少应用中都是常见的。使用indexof()和substring()来分析字符串容易致使 stringindexoutofboundsexception。而使用stringtokenizer类来分析字符串则会容易一些,效率也会高一些。
例子:
public class ust { void parsestring(string string) { int index = 0; while ((index = string.indexof(".", index)) != -1) { system.out.println (string.substring(index, string.length())); } } }
参考资料:
graig larman, rhett guthrie: "java 2 performance and idiom guide"
prentice hall ptr, isbn: 0-13-014260-3 pp. 282 – 283
十7、使用条件操做符替代"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); } }
十8、使用条件操做符代替"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; }
十9、不要在循环体中实例化变量
在循环体中实例化临时变量将会增长内存消耗
例子:
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); } } }
二10、肯定 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
二11、尽量的使用栈变量
若是一个变量须要常常访问,那么你就须要考虑这个变量的做用域了。static? local?仍是实例变量?访问静态变量和实例变量将会比访问局部变量多耗费2-3个时钟周期。
例子:
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; }
更正:
若是可能,请使用局部变量做为你常常访问的变量。
你能够按下面的方法来修改getsum()方法:
void getsum (int[] values) { int sum = _sum; // temporary local variable. for (int i=0; i < value.length; i++) { sum += value[i]; } _sum = sum; }
参考资料:
peter haggar: "practical java - programming language guide".
addison wesley, 2000, pp.122 – 125
二12、不要老是使用取反操做符(!)
取反操做符(!)下降程序的可读性,因此不要老是使用。
例子:
public class dun { boolean method (boolean a, boolean b) { if (!a) return !a; else return !b; } }
更正:
若是可能不要使用取反操做符(!)
二十3、与一个接口 进行instanceof操做
基于接口的设计一般是件好事,由于它容许有不一样的实现,而又保持灵活。只要可能,对一个对象进行instanceof操做,以判断它是否某一接口要比是否某一个类要快。
例子:
public class insof { private void method (object o) { if (o instanceof interfacebase) { } // better if (o instanceof classbase) { } // worse. } } class classbase {} interface interfacebase {}
转载: http://www.cnblogs.com/chinafine/articles/1787118.html
for(int i=0;i<list.size();i++)
for(int i=0,len=list.size();i<len;i++)
String str="abc"; if(i==1){ list.add(str);}
if(i==1){String str="abc"; list.add(str);}
public static Credit getNewCredit() { return new Credit(); }
private static Credit BaseCredit = new Credit(); public static Credit getNewCredit() { return (Credit)BaseCredit.clone(); }
Map<String, String[]> paraMap = new HashMap<String, String[]>(); for( Entry<String, String[]> entry : paraMap.entrySet() ) { String appFieldDefId = entry.getKey(); String[] values = entry.getValue(); }
System.out.println(2.00 -1.10);//0.8999999999999999
System.out.println(200-110);//90
System.out.println(new BigDecimal("2.0").subtract(new BigDecimal("1.10")));// 0.9
long microsPerDay = 24 * 60 * 60 * 1000 * 1000;// 正确结果应为:86400000000 System.out.println(microsPerDay);// 实际上为:500654080
long microsPerDay = 24L * 60 * 60 * 1000 * 1000;
System.out.println(0x80);//128 //0x81看做是int型,最高位(第32位)为0,因此是正数 System.out.println(0x81);//129 System.out.println(0x8001);//32769 System.out.println(0x70000001);//1879048193 //字面量0x80000001为int型,最高位(第32位)为1,因此是负数 System.out.println(0x80000001);//-2147483647 //字面量0x80000001L强制转为long型,最高位(第64位)为0,因此是正数 System.out.println(0x80000001L);//2147483649 //最小int型 System.out.println(0x80000000);//-2147483648 //只要超过32位,就须要在字面常量后加L强转long,不然编译时出错 System.out.println(0x8000000000000000L);//-9223372036854775808
System.out.println(Long.toHexString(0x100000000L + 0xcafebabe));// cafebabe
System.out.println(Long.toHexString(0x100000000L + 0xcafebabeL));// 1cafebabe
System.out.println((int)(char)(byte)-1);// 65535
int i = c & 0xffff;//实质上等同于:int i = c ;
int i = (short)c;
char c = (char)(b & 0xff);// char c = (char) b;为有符号扩展
((byte)0x90 & 0xff)== 0x90
char x = 'X'; int i = 0; System.out.println(true ? x : 0);// X System.out.println(false ? i : x);// 88
final int i = 0; System.out.println(false ? i : x);// X
public class T { public static void main(String[] args) { System.out.println(f()); } public static T f() { // !!1.4不能编译,但1.5能够 // !!return true?new T1():new T2(); return true ? (T) new T1() : new T2();// T1 } } class T1 extends T { public String toString() { return "T1"; } } class T2 extends T { public String toString() { return "T2"; } }