Java程序性能優化

一、避免在循環條件中使用復雜表達式


在不做編譯優化的情況下,在循環中,循環條件會被反復計算,如果不使用復雜表達式,而使循環條件值不變的話,程序將會運行的更快。

例子:
import java.util.vector;
class cel {
????void method (vector vector) {
????????for (int i = 0; i < vector.size (); i++)??// violation
????????????; // ...
????}
}

更正:
class cel_fixed {
????void method (vector vector) {
????????int size = vector.size ()
????????for (int i = 0; i < size; i++)
????????????; // ...
????}
}

二、為vectors?和 hashtables定義初始大小


jvm為vector擴充大小的時候需要重新創建一個更大的數組,將原原先數組中的內容復制過來,最后,原先的數組再被回收。可見vector容量的擴大是一個頗費時間的事。
通常,默認的10個元素大小是不夠的。你最好能準確的估計你所需要的最佳大小。

例子:
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

三、在finally塊中關閉stream


程序中使用到的資源應當被釋放,以避免資源泄漏。這最好在finally塊中去做。不管程序執行的結果如何,finally塊總是會執行的,以確保資源的正確關閉。
?????????
例子:
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

四、使用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
????????}
????}
}
?????????
更正:
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

五、讓訪問實例內變量的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

六、避免不需要的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");
????}
}

七、避免不需要的造型操作


所有的類都是直接或者間接繼承自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

八、如果只是查找單個字符的話,用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

九、使用移位操作來代替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;???????// 不能轉換成位移操作
????}
}

十、使用移位操作代替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;???????// 不能轉換
????}
}

十一、在字符串相加的時候,使用?代替 " ",如果該字符串只有一個字符的話



例子:
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???
????}
}

十二、不要在循環中調用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);
}

十三、將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

十四、對于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");
????}
}

十五、對于常量字符串,用string?代替 stringbuffer


常量字符串并不需要動態改變長度。
例子:
public class usc {
????string method () {
????????stringbuffer s = new stringbuffer ("hello");
????????string t = s + "world!";
????????return t;
????}
}

更正:
把stringbuffer換成string,如果確定這個string不會再變的話,這將會減少運行開銷提高性能。

十六、用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

十七、使用條件操作符替代"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

二十一、盡可能的使用棧變量


如果一個變量需要經常訪問,那么你就需要考慮這個變量的作用域了。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

二十二、不要總是使用取反操作符(!)


取反操作符(!)降低程序的可讀性,所以不要總是使用。

例子:
public class dun {
????boolean method (boolean a, boolean b) {
????????if (!a)
????????????return !a;
????????else
????????????return !b;
????}
}

更正:
如果可能不要使用取反操作符(!)

二十三、與一個接口?進行instanceof操作


基于接口的設計通常是件好事,因為它允許有不同的實現,而又保持靈活。只要可能,對一個對象進行instanceof操作,以判斷它是否某一接口要比是否某一個類要快。

例子:
public class insof {
????private void method (object o) {
????????if (o instanceof interfacebase) { }??// better
????????if (o instanceof classbase) { }???// worse.
????}
}

class classbase {}
interface interfacebase {}

?
?

轉載于:https://www.cnblogs.com/suncoolcat/p/3320013.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/259387.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/259387.shtml
英文地址,請注明出處:http://en.pswp.cn/news/259387.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

asp.net表單提交方法:GET\POST介紹

表單form的提交有兩種方式&#xff0c;一種是get的方法&#xff0c;一種是post 的方法&#xff0c;如果沒有特殊指定&#xff0c;默認為post。看下面代碼,理解ASP.NET Get和Post兩種提交的區別: 1.< form id"form1" method"get" runat"server"…

各種排序算法總結

轉載&#xff1a;http://blog.csdn.net/warringah1/article/details/8951220 明天就要去參加阿里巴巴的實習生筆試了&#xff0c;雖然沒想著能進去&#xff0c;但是態度還是要端正的&#xff0c;也沒什么可以準備的&#xff0c;復習復習排序吧。 1 插入排序 void InsertSort(in…

CentOS7 上安裝 Zookeeper-3.4.9 服務

在 CentOS7 上安裝 zookeeper-3.4.9 服務1、創建 /usr/local/services/zookeeper 文件夾&#xff1a; mkdir -p /usr/local/services/zookeeper 2、進入到 /usr/local/services/zookeeper 目錄中&#xff1a; cd /usr/local/services/zookeeper 3、下載 zookeeper-3.4.9.…

c語言在程序中顯示現在星期幾,C語言程序設計: 輸入年月日 然后輸出是星期幾...

該樓層疑似違規已被系統折疊 隱藏此樓查看此樓#include main(){int year,month,day0,a,b,week,c,i,sum0,days,d;printf("please input year,month,days\n");scanf("%d,%d,%d",&year,&month,&days);for(i1;i{if (year%40){if(year%1000){if (ye…

static之用法

本文轉載于http://www.cnblogs.com/stoneJin/archive/2011/09/21/2183313.html 在C語言中&#xff0c;static的字面意思很容易把我們導入歧途&#xff0c;其實它的作用有三條。 &#xff08;1&#xff09;先來介紹它的第一條也是最重要的一條&#xff1a;隱藏。 當我們同時編譯…

HTTP響應報文與工作原理詳解

HTTP 是一種請求/響應式的協議&#xff0c;即一個客戶端與服務器建立連接后&#xff0c;向服務器發送一個請求;服務器接到請求后&#xff0c;給予相應的響應信息。 超文本傳輸協議(Hypertext Transfer Protocol&#xff0c;簡稱HTTP)是應用層協議。HTTP 是一種請求/響應式的協議…

優先隊列priority_queue 用法詳解

轉載&#xff1a; 1.優先隊列priority_queue 用法詳解 2.STL系列之五 priority_queue 優先級隊列 優先隊列是隊列的一種&#xff0c;不過它可以按照自定義的一種方式&#xff08;數據的優先級&#xff09;來對隊列中的數據進行動態的排序 每次的push和pop操作&#xff0c;隊…

android自定義畫板,android 自定義控件 -- 畫板

如圖&#xff1a;package com.example.myview;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Path;import android.graphics.Paint.Style;import android.util.Attrib…

postgreSQl pathman 用法語句總結

2019獨角獸企業重金招聘Python工程師標準>>> --新建主表 create table part_test(id int, info text, crt_time timestamp not null); --插入測試數據 insert into part_test select id,md5(random()::text),clock_timestamp() (id|| hour)::interval from generat…

Oracle查詢筆記

-- tanslate(str,from_str,to_str) -- 將str中的from_str替換成to_str select translate(hello,e,o) t from dual;-- instr(str,des_str) -- 可以實現like功能 select instr(hello,g),instr(hello,h),instr(hello,l) from dual; -- decode(value,s1,r1,s2,r2,default) -- 類似于…

全排列算法及實現

轉載&#xff1a; 1.http://blog.csdn.net/hackbuteer1/article/details/6657435 2.http://blog.sina.com.cn/s/blog_9f7ea4390101101u.html 3.http://www.slyar.com/blog/stl_next_permutation.html 4.http://www.cplusplus.com/reference/algorithm/next_permutation/ 5…

ssh配置文件詳解

配置“/etc/ssh/sshd_config”文件 “/etc/ssh/sshd_config”是OpenSSH的配置文件&#xff0c;允許設置選項改變這個daemon的運行。這個文件的每一行包含“關鍵詞&#xff0d;值”的匹配&#xff0c;其中“關鍵詞”是忽略大小寫的。下面列出來的是最重要的關鍵詞&#xff0…

EC+VO+SCOPE for ES3

詞法環境 詞法作用域 詞法作用域&#xff08;lexcical scope&#xff09;。即JavaScript變量的作用域是在定義時決定而不是執行時決定&#xff0c;也就是說詞法作用域取決于源碼。 詞法環境 用于定義特定變量和函數標識符在ECMAScript代碼的詞法嵌套結構上的關聯關系&#xff0…

你真的會寫二分檢索嗎?

轉載&#xff1a;http://blog.chinaunix.net/uid-1844931-id-3337784.html 前幾天在論壇上看到有統計說有80%的程序員不能夠寫對簡單的二分法。二分法不是很簡單的嗎&#xff1f; 這難道不是聳人聽聞&#xff1f; 其實&#xff0c;二分法真的不那么簡單&#xff0c;尤其是二…

android listview動態加載網絡圖片不顯示,Android Listview異步動態加載網絡圖片

Android Listview異步動態加載網絡圖片詳見&#xff1a; http://blog.sina.com.cn/s/blog_62186b460100zsvb.html標簽&#xff1a; Android SDK代碼片段(5)[代碼] (1)定義類MapListImageAndText管理ListViewItem中控件的內容01 package com.google.zxing.client.android.AsyncL…

C#-面向對象的多態思想 ---ShinePans

總結: 多態是面向對象的核心.---------能夠理解為一個方法,多種實現, 在這里能夠用虛方法,抽象類,接口能夠實現多態 1.首先利用接口來實現多態: 接口相當于"功能,"接口能夠實現多繼承,分為 顯式實現接口和隱式實現接口 keyword為interface格式: interface 接口名 { …

wxpy 0.1.2微信機器人 / 優雅的微信個人號API

微信機器人 / 優雅的微信個人號API&#xff0c;基于 itchat&#xff0c;全面優化接口&#xff0c;更有 Python 范兒。用來干啥一些常見的場景控制路由器、智能家居等具有開放接口的玩意兒跑腳本時自動把日志發送到你的微信加群主為好友&#xff0c;自動拉進群中跨號或跨群轉發消…

c++中try catch的用法

在c中&#xff0c;可以直接拋出異常之后自己進行捕捉處理&#xff0c;如&#xff1a;&#xff08;這樣就可以在任何自己得到不想要的結果的時候進行中斷&#xff0c;比如在進行數據庫事務操作的時候&#xff0c;如果某一個語句返回SQL_ERROR則直接拋出異常&#xff0c;在catch塊…

const in c and cpp

http://c-faq.com/ansi/constasconst.html 轉載于:https://www.cnblogs.com/invisible/p/3333575.html

android ndk調用出錯,由于Android-NDK應用程序的權限問題,為什么fopen在本地方法中失敗?...

errno 0;FILE *fp;fp fopen("jigar.txt","wb");if(fp NULL)__android_log_print(ANDROID_LOG_ERROR, APPNAME, "FOPEN FAIL with %d",errno);else__android_log_print(ANDROID_LOG_ERROR, APPNAME, "FOPEN pass ");它得到失敗&…