我有一个程序需要用 Java 编写的大量查询,选择 JDBC 来操作 mysql db。我的代码框架如下:
PreparedStatement stmt = conn.preparedStatement(
"SELECT name FROM users WHERE id = ?" )
Iterator<String, Double> it = map.entrySet().iterator();
//map is relativelly large, holding about 100,000 records,
//each need to query mysql, and do some computing
//I record the time consuming of query & computing
while ( it.hasNext() ) {
String id = it.next().getKey();
stmt.setString(1, id); //set the missing param with id
long queryStart = System.currentTimeMillis();
ResultSet rs = st.executeQuery();
long queryEnd = System.currentTimeMillis();
while ( rs.next() ) {
//computing
}
rs.close();
st.clearParameters();
long computeEnd = System.currentTimeMillis();
System.out.println(index+" has done...");
System.out.println(" query time: "+ (queryEnd-queryStart));
System.out.println(" compute time: "+ (computeEnd-queryEnd));
}
大约 100-200 次循环的性能在一开始就很好。但之后突然下降。
控制台窗口中打印的结果是:
1 has done...
query time: 0
compute time: 0
2 has done...
query time: 0
compute time: 0
3 has done...
...
...
191 has done...
query time: 1
compute time: 0
192 has done...
query time: 0
compute time: 1
193 has done...
query time: 1018
compute time: 0
194 has done...
query time: 1142
compute time: 0
195 has done...
query time: 1122
compute time: 0
我的数据库位于本地主机。为什么会发生这种情况,什么会如此显着地影响性能?
我怎样才能提高性能?
顺便说一句:Object Statement, Connection ...是在java.sql中定义的,我没有使用com.mysql.jdbc版本,我不知道有什么区别。