ITeye博客

PreparedStatement与Statement性能详细对比

LucasLee · 2007-01-22 22:28 · 技术话题 · PostgreSQL · SQL · MySQL · Oracle · Markdown

我对PreparedStatement和Statement的性能测试了一下:
 测试代码如下:

java 代码

 

  1. Connection con = getOraConnection();
  2. String sql = "select id,name from test where id=";
  3. String tempSql;
  4. int count = 1000;
  5. long time = System.currentTimeMillis();
  6. for (int i = 0; i < count; i++) {
  7. Statement st = con.createStatement();
  8. tempSql=sql+(int) (Math.random() * 100);
  9. st.executeQuery(tempSql);
  10. st.close();
  11. }
  12. System.out.println("st cost:" + (System.currentTimeMillis() - time));
  13. String psql = "select id,name from test where id=?";
  14. time = System.currentTimeMillis();
  15. for (int i = 0; i < count; i++) {
  16. int id=(int) (Math.random() * 100);
  17. PreparedStatement pst = con.prepareStatement(psql);
  18. pst.setBigDecimal(1, new BigDecimal(id));
  19. pst.executeQuery();
  20. pst.close();
  21. }
  22. System.out.println("pst cost:" + (System.currentTimeMillis() - time));
  23. con.close();

test表很简单,id int,name varchar(50).
对几种数据库和相应驱动程序进行测试,结果如下(ms):
oracle:        1235    1109
MSSQL2000(JTDS):391    453
MSSQL2000(MS):    453    640
Mysql5:        391    891
PostgreSQL8.1:   1078    1047
结论:
1.单并发情况下,oracle--PostgreSQL--MSSQL--MySQL的性能依次增高;
2.MySQL不支持Prepared Statement特性,已在其驱动程序的文档中证实,所以在MySQL里使用 PreparedStatement的性能尤其低,可以比Statement慢一倍以上。
而MSSQL2000下,PreparedStatement比Statement慢;
Oracle,PostgreSQL对它的支持最好,使用PreparedStatement性能比Statement高。

评论(2)

  1. #2 楼 · gongmingwind · 2008-06-24 10:47

    用事实说话!

  2. #1 楼 · meikefu · 2008-03-19 15:42

    没有发挥预编译的威力,,oracle中应该有50%的性能提升不可能只提高那么一点PreparedStatement pst = con.prepareStatement(psql); for (int i = 0; i < count; i++) {
    int id=(int) (Math.random() * 100);
    pst.setBigDecimal(1, new BigDecimal(id));
    pst.executeQuery();
    }
    pst.close();

评论功能维护中,当前仅展示历史评论。