一、避免在循環條件中使用複雜表達式
#在不做編譯最佳化的情況下,在循環中,循環條件會被反覆計算,如果不使用複雜表達式,而使循環條件值不變的話,程式將會運行的更快。
範例:
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++) ; // ... } }
#2、為'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);
三、在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區塊
四、使用'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); } }
#五、讓存取實例內變數的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; }
六、避免不需要的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"); } }
修正: 與刪除作業所刪除的中刪除作業。
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; } }
八、如果只是找出單一字元的話,用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)) { // ... } } }
、使用移位操作來代替'a / b'操作
"/"是一個很「昂貴」的操作,使用移位操作將會更快更有效。
範例:
public class sp { public static final int num = 16; public void calculate(int a) { int p = a / 4; // should be replaced with "a >> 2". int p2 = a / 8; // should be replaced with "a >> 3". int temp = a / 3; } }修正:
public class sp { public static final int num = 16; public void calculate(int a) { int p = a >> 2; int p2 = 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) {} }
十四、对于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())); } } }
十七、使用条件操作符替代"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; }
二十一、尽可能的使用栈变量
如果一个变量需要经常访问,那么你就需要考虑这个变量的作用域了。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; }
二十二、不要总是使用取反操作符(!)
取反操作符(!)降低程序的可读性,所以不要总是使用。
例子:
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 {}
以上是Java中關於程式效能最佳化的實例講解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

Dreamweaver Mac版
視覺化網頁開發工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。