例一:應用具有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()一次性完成