今天girlfriend到公司交作业(还是培训期),她们的pm让她们在数据读取的使用FOR循环(如例test1),问之,为啥,说pm说了,这样好,还拿了一本pm给的Effective Java,说看了就明白,废话不多说,看之,原来就这样一条,如果在循环体外不需要继续使用的变量建议使用FOR循环,并且在for的第一部分初始化,这样一来循环结束以后就会自动回收,但是大家仔细思考一下,这地方能利用这条原则??,RESULTSET
是跟着statement走的,当你关闭statement,resultset会被关闭,使你使用FOR循环没有任何好处,相反,WHILE要更快,使用for是弄巧成拙.例子如下,大家也看到while要比for快将近3倍,记录为1000条左右.写这个例子,希望大家不要犯类似的错.....
package jp.gibraltar.bnas.branch.accountclose.closecheck;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import jp.gibraltar.util.DBUtil;
import junit.framework.TestCase;
/**
* @author sfluo
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class CloseCheckInputActionTest extends TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(CloseCheckInputActionTest.class);
}
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
}
public final void testExecuteCheckInput() {
CloseCheckInputActionTest test = new CloseCheckInputActionTest();
System.out.println(System.currentTimeMillis());
test.test1();
System.out.println(System.currentTimeMillis());
test.test2();
System.out.println(System.currentTimeMillis());
}
void test1() {
Connection conn = DBUtil.getConnection();
Vector vs = new Vector();
try {
Statement stmt = conn.createStatement();
for (ResultSet rs = stmt
.executeQuery("select * from accesslog_bnas "); rs.next();) {
vs.add(rs.getString(1));
}
stmt.close();
conn.close();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void test2() {
Connection conn = DBUtil.getConnection();
Vector vs = new Vector();
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from accesslog_bnas ");
while (rs.next()) {
vs.add(rs.getString(1));
}
stmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1100141162919
1100141174035
1100141178942