公告 |
求真务实打基础, 宁缺毋滥读好书。
数据挖掘青年(DMman) |
链接 |
|
Blog信息 |
blog名称:DMman(数据挖掘青年) 日志总数:102 评论数量:564 留言数量:57 访问次数:1757693 建立时间:2007年4月9日 |

| |
[Java SE]Java程序性能优化 文章收藏
数据挖掘青年 发表于 2007/11/21 8:47:16 |
不错的东西,先贴过来 有空慢慢研究:)以前用JTable显示数据库中数据的使用。开始使用Vector过渡ResultSet中的数据,速度慢的要死;后来改成了数组,提高了五六倍速度!
一、避免在循环条件中使用复杂表达式在不做编译优化的情况下,在循环中,循环条件会被反复计算,如果不使用复杂表达式,而使循环条件值不变的话,程序将会运行的更快。例子: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-5Addison-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 Idiomsfor 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 {} |
|
不要使用println及字符串连接 文章收藏
数据挖掘青年发表评论于2007/11/28 18:07:04 |
不要使用println及字符串连接。通常为了调试方便,开发者喜欢在可能的所有地方都加上 System.out.println,也许还会提醒自己回过头来再来删除,但有些时候,经常会忘了删除或者不愿意删除它们。既然使用 System.out.println是为了测试,那么测试完之后,为什么还要留着它们呢,因为在删除时,很可能会删除掉真正有用的代码,所以不能低估 System.out.println危害啊,请看下面的代码:
public class BadCode { public static void calculationWithPrint(){ double someValue = 0D; for (int i = 0; i < 10000; i++) { System.out.println(someValue = someValue + i); } } public static void calculationWithOutPrint(){ double someValue = 0D; for (int i = 0; i < 10000; i++) { someValue = someValue + i; } } public static void main(String [] n) { BadCode.calculationWithPrint(); BadCode.calculationWithOutPrint(); } }
从测试中可以发现,方法calculationWithOutPrint()执行用了0.001204秒,作为对比,方法calculationWithPrint()执行可是用了10.52秒。
要避免浪费CPU时间,最好的方法是引入像如下的包装方法:
public class BadCode { public static final int DEBUG_MODE = 1; public static final int PRODUCTION_MODE = 2; public static void calculationWithPrint(int logMode){ double someValue = 0D; for (int i = 0; i < 10000; i++) { someValue = someValue + i; myPrintMethod(logMode, someValue); } } public static void myPrintMethod(int logMode, double value) { if (logMode > BadCode.DEBUG_MODE) { return; } System.out.println(value); } public static void main(String [] n) { BadCode.calculationWithPrint(BadCode.PRODUCTION_MODE); } }
另外,字符串连接也是浪费CPU时间的一个大头,请看下面的示例代码:
public static void concatenateStrings(String startingString) { for (int i = 0; i < 20; i++) { startingString = startingString + startingString; } } public static void concatenateStringsUsingStringBuffer(String startingString) { StringBuffer sb = new StringBuffer(); sb.append(startingString); for (int i = 0; i < 20; i++) { sb.append(sb.toString()); } }
在测试中可发现,使用StringBuffer的方法只用了0.01秒执行完毕,而使用连接的方法则用了0.08秒,选择显而易见了。 |
|
回复:Java程序性能优化 文章收藏
真不准发表评论于2007/11/21 10:23:24 |
不错的文章,不过用移位替代 *,有点过份。。
以下为blog主人的回复:
我看java的源码中,乘除2的倍数的时候都用的移位操作。应该是考虑时间复杂度的问题,普通的乘法要转换成累加进行,这样代价是移位操作的好多倍。 |
|
回复:Java程序性能优化 文章收藏
数据挖掘青年发表评论于2007/11/21 8:52:17 |
1 使用非阻塞I/O
版本较低的JDK不支持非阻塞I/O API。为避免I/O阻塞,一些应用采用了创建大量线程的办法(在较好的情况下,会使用一个缓冲池)。这种技术可以在许多必须支持并发I/O流的应用中见到,如Web服务器、报价和拍卖应用等。然而,创建Java线程需要相当可观的开销。
JDK 1.4引入了非阻塞的I/O库(java.nio)。如果应用要求使用版本较早的JDK,在这里有一个支持非阻塞I/O的软件包。
2 慎用异常
异常对性能不利。抛出异常首先要创建一个新的对象。Throwable接口的构造函数调用名为fillInStackTrace()的本地(Native)方法,fillInStackTrace()方法检查堆栈,收集调用跟踪信息。只要有异常被抛出,VM就必须调整调用堆栈,因为在处理过程中创建了一个新的对象。
异常只能用于错误处理,不应该用来控制程序流程。
3 不要重复初始化变量
默认情况下,调用类的构造函数时, Java会把变量初始化成确定的值:所有的对象被设置成null,整数变量(byte、short、int、long)设置成0,float和double变量设置成0.0,逻辑值设置成false。当一个类从另一个类派生时,这一点尤其应该注意,因为用new关键词创建一个对象时,构造函数链中的所有构造函数都会被自动调用。
4 尽量指定类的final修饰符
带有final修饰符的类是不可派生的。在Java核心API中,有许多应用final的例子,例如java.lang.String。为String类指定final防止了人们覆盖length()方法。
另外,如果指定一个类为final,则该类所有的方法都是final。Java编译器会寻找机会内联(inline)所有的final方法(这和具体的编译器实现有关)。此举能够使性能平均提高50%。
5 尽量使用局部变量
调用方法时传递的参数以及在调用中创建的临时变量都保存在栈(Stack)中,速度较快。其他变量,如静态变量、实例变量等,都在堆(Heap)中创建,速度较慢。另外,依赖于具体的编译器/JVM,局部变量还可能得到进一步优化。 |
|
回复:Java程序性能优化 文章收藏
数据挖掘青年发表评论于2007/11/21 8:51:48 |
Java程序性能和速度优化实例美国 硅谷 David Lee
例一:应用具有I/O Buffer功能Class
import java.io.*;
public class IoTest {
public static void main(String args[]) {
try {
FileReader fr = new FileReader(args[0]);
BufferedReader br = new BufferedReader(fr);
while ( br.readLine() != null ) {
System.out.println(" The file content are :" + br.readLine());
}
fis.close();
} catch ( IOException ioe ) {
System.out.println("The I/O exception is " + ioe);
}
}
}
在上例中,程序使用了具有Buffer功能的Class,使得Disk I/O的读取速度大大提高。BufferedReader 是取代DataInputStream 而提高读写速度的Java Class。在新的Java版本中,已不建议使用 DataInputStream,因为其读写是基于字符为单位的。
例二:字符串运算处理
public class StringOperation {
public static void main(String args[]) {
String sqlQuery = null;
String sqlCondition = " conditionC = conditionD ");
StringBuffer sb = new StringBuffer();
sb.append("select * from database table where ");
sb.append(" conditionA = conditionB and ");
if ( ! sqlCondition.equals(null) {
sb.append(sqlCondition);
} else {
sb.append(" conditionE = conditionF ");
}
sqlQuery = sb.toString();
// Then connect to the database then excute the database query
// .......
}
}
在上例中,使用StingBuffer class来完成数据库查询建立,避免使用String class的"+="操作,以减少JVM在内存中创建新的对象,占用资源,增加JVM回收资源负担。读者可以使用Java Proflier功能来具体比较使用不同的String操作,JVM需要完成多少资源回收和运行时间。因此在JVM中对String直接进行"+="是非常昂贵的运算。
例三:处理昂贵的数据库初始化
目前许多网站可以透过Web服务器查询数据库,如何提高数据库查询速度成为许多程序员关注的问题。在Java Servlets或JSP中可以通过init() 或Jspinit()来实现,以下是一具体Java Servlet与数据库对话实例。
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DatabaseServlet extends HttpServlet {
public void init( ServletConfig conf) throws ServletException {
super.init(conf);
Connection conn = null;
try {
Class.forName("sun.jdbc.odbc.JdcOdbcDriver");
Conn = DriverManager.getConnection("jdbc:odbc:yourDSN,"","");
} catch ( SQLException sqle ) {
System.err.println("your error exception is " + sqle);
} catch ( ClassNotFoundException cnfe ) {
System.err.println("your error exception is " + cnfe);
}
}
public void doGet( HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
res.setContentType("text/html");
ServletOutputStream out = null;
// Your HTML formatter
out.println(" Your HTML");
try {
Statement stmt = conn.creatStatement();
ResultSet rs = stmt.excuteQuery("select * from yourDatabasetable ");
while ( rs.next() ) {
// Processing your data
}
} catch ( SQLException sqle ) {
out.println("The SQL error is " + sqle);
}
// output your processing result to HTML page
out.println(" your HTML");
rs.close();
stmt.close();
}
public void destroy() {
try {
conn.close();
} catch ( SQLException sqle ) {
System.err.println("your SQL error is " + sqle);
}
}
}
在上例中,由于Java Servlet运行机制的特点,将昂贵的数据库初始化运算在整个Servlet运行中仅只调用一次的init()中完成,以减少不必要的重复性数据库运算。读者可以根据应用的具体情况,甚至将数据库的Statement和ResultSet部分移至init()中完成,或者调用PreparedStatement与CallableStatement来优化数据库的运算。同时,对数据库的连接的关闭由destroy()一次性完成 |
|
» 1 »
|