欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入
9. 异常在需要抛出的地方抛出,try catch能整合就整合
try{ some.method1();//DifficultforJavac }catch(method1Exceptione){//andtheJVMruntime //Handleexception1//tooptimizethis }//code try{ some.method2(); }catch(method2Exceptione){ //Handleexception2 } try{ some.method3(); }catch(method3Exceptione){ //Handleexception3 }已下代码 更容易被编译器优化
try{ some.method1();//Easiertooptimize some.method2(); some.method3(); }catch(method1Exceptione){ //Handleexception1 }catch(method2Exceptione){ //Handleexception2 }catch(method3Exceptione){ //Handleexception3 }10. For循环的优化
Replace… for(inti=0;i<collection.size();i++){ … } with… for(inti=0,n=collection.size();i<n;i++){ … }11. 字符串操作优化
在对字符串实行+操作时,最好用一条语句
//Yoursourcecodelookslike… Stringstr=“profit=revenue(”revenue “?cost(”cost““; //编译方法 Stringstr=newStringBuffer().append(“profit=revenue(“). append(revenue).append(“?cost(“). append(cost).append(““).toString(); 在循环中对字符串操作时改用StringBuffer.append()方法 Stringsentence=“”; for(inti=0;i<wordArray.length;i++){ sentence+=wordArray[i]; }优化为
StringBufferbuffer=newStringBuffer(500); for(inti=0;i<wordArray.length;i++){ buffer.append(wordArray[i]); } Stringsentence=buffer.toString();12. 对象重用(特别对于大对象来说)
public classPoint { publicintx; publicinty; publicPoint() { this(0,0); } }优化为:
publicclassComponent { privateintx; privateinty; publicPointgetPosition() { Pointrv=newPoint();//CreateanewPoint rv.x=x;//Updateitsstate rv.y=y; returnrv; } } //ProcessanarrayofComponentpositions… for(inti=0;i<componentArray.length;i++){ Pointposition=componentArray[i].getPosition(); //Processpositionvalue… //Note:APointobjectiscreatedforeachiteration //oftheloop… }可再次优化,仅使用一个类对象:)
public classComponent { privateintx; privateinty; publicPointgetPosition(Pointrv) { if(rv==null)rv=newPoint(); rv.x=x;//Updateitsstate rv.y=y; returnrv; } //Createasinglepointobjectandreuseit… Pointp=newPoint(); for(inti=0;i<componentArray.length;i++){ Pointposition=componentArray[i].getPosition(p); //Processpositionvalue… //Note:OnlyonePointobjectisevercreated. }13. J2EE相关
a) 尽量不要将大对象放到HttpSession或其他须序列化的对象中,并注意及时清空Session
b) 使用预编译语句prepareStatement代替createStatement
c) 尽可能使用连接池
d) 能使用Cache就使用Cache,具体实现可参考jive(CacheCacheableCacheObjectCacheSizesDefaultCacheLinkdListLinkdListNode)或ofbiz(org.ofbiz.core.util. UtilCache.Java)
[1][2]
也许不是自己该去发挥的地方,还是让自己到最适合自己战斗的方面去吧!勇敢的接受自己的失败,