PreparedStatements CAN be faster than Statements, but there is no guarantee of it. If the database doesn't cache the PreparedStatement then it will get re-compiled every time, leading to comparable execution time between the two. However when the database DOES cache them, you get a nice performance gain. The other big advantage of using PreparedStatements is the ability to parameterize the values by the use of "?". You don't have to worry about whether your database uses single or double quotes to delimit strings, or how to format date values. You simply use "?" in the PreparedStatement and then to "setString()" or "setDate()" to set the parameter and the underlying vendor classes handle everything for you. It makes the code much more portable (database independance).
Joined: Sep 12, 2003
If the database does not cache the prepared statement then is the time taken to execute the Statement and PreparedStatement equal?
Wayne L Johnson
Joined: Sep 03, 2003
There are a lot of factors that can affect the time: network traffic, what database you are running, database indexes, etc. The best thing for you to do is write a simple app that inserts several thousand records into the database using prepared statements, and several thousand using 'regular' statements. See how long each set takes. The difference may be negligable, or it may be irrelevant considering what else your real application does. The performance considerations aside, there is still great value in using PreparedStatements for the ease with which you can work with String and Date values, not to mention BLOB/CLOB objects or database-specific objects. Go with PreparedStatements.