I am trying to use JDBC prepared statements and the performance is worse compared to regular statements.
To illustrate, there are 2 code samples below, one with preparedstatement and the 2nd with regular statement.
WITH PREPARED STATEMEMT:
for (int i=0;i<count;++i){
long sta1 = System.currentTimeMillis();
stmt = con.prepareStatement("SELECT collab_subkey , version_id FROM E2sc_hana_psr.ppff_collab_mod WHERE collab_subkey = ?");
long sta2 = System.currentTimeMillis();
stmt.setString(1, "testkey");
rs = stmt.executeQuery();
long sta3 = System.currentTimeMillis();
while (rs.next())
System.out.println(rs.getString(1));
long sta4 = System.currentTimeMillis();
rs.close();
stmt.close();
long sta5 = System.currentTimeMillis();
execTime += (sta3 - sta2);
prepTime += sta2 - sta1;
closeTime += sta5 - sta4;
}
System.out.println("TOTAL PREP TIME:" + prepTime);
System.out.println("TOTAL EXEC TIME:" + execTime);
System.out.println("TOTAL CLOSE TIME:" + closeTime);
WITH REGULAR STATEMENT
for (int i=0;i<count;++i){
long sta1 = System.currentTimeMillis();
stmt = con.createStatement();
long sta2 = System.currentTimeMillis();
rs = stmt.executeQuery("SELECT collab_subkey , version_id FROM E2sc_hana_psr.ppff_collab_mod WHERE collab_subkey = 'test'");
long sta3 = System.currentTimeMillis();
while (rs.next())
System.out.println(rs.getString(1));
long sta4 = System.currentTimeMillis();
rs.close();
stmt.close();
long sta5 = System.currentTimeMillis();
execTime += (sta3 - sta2);
prepTime += sta2 - sta1;
closeTime += sta5 - sta4;
}
System.out.println("TOTAL PREP TIME:" + prepTime);
System.out.println("TOTAL EXEC TIME:" + execTime);
System.out.println("TOTAL CLOSE TIME:" + closeTime);
Now when I run my test code for 1000 times in the for loop, here are the timings
WITH PREPAREDSTATEMENT:
TOTAL PREP TIME:1489
TOTAL EXEC TIME:1442
TOTAL CLOSE TIME:1278
WITH REGULAR STATEMENT
TOTAL PREP TIME:17
TOTAL EXEC TIME:1611
TOTAL CLOSE TIME:6
Its clear that preparedstatement execution takes more time because, the PREPARE and CLOSE calls are taking almost 2/3rds of the entire time.
Is there anything I am missing here? This is contrary to the popular belief that prepared statements are faster that regular statements.