今天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();
}
}
}
print
1100141162919
1100141174035
1100141178942
闽公网安备 35060202000074号