Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL prepared statements vs simple queries performance

Tags:

mysql

I made a few tests, first I tested mysql prepared statement with $pdo->prepare() and $insert_sth->execute() for 10k inserts (with named parameters if it matters), and it took 301s.

After that I made simple insert queries and inserting each time for the same 10k inserts too and it took 303s.

So I would like to know: does prepared statements really give performance benefits? Because my tests didn't show it , or I have to optimize my prepared statements version in order for them to be they faster?

I can give my source code if it's needed.

like image 656
Centurion Avatar asked Aug 05 '10 07:08

Centurion


People also ask

Which is faster statement or PreparedStatement?

Prepared statements are much faster when you have to run the same statement multiple times, with different data. Thats because SQL will validate the query only once, whereas if you just use a statement it will validate the query each time.

Are prepared statements slower?

Prepared statements are FASTER then non-prepared statements if you repeatedly use the same statement with multiple sets of data.

Are prepared statements better?

Why use prepared statements? There are numerous advantages to using prepared statements in your applications, both for security and performance reasons. Prepared statements can help increase security by separating SQL logic from the data being supplied.

Why are prepared statements preferred over insert queries?

It is recommended to use PreparedStatement if you are executing a particular SQL query multiple times. It gives better performance than Statement interface. Because, PreparedStatement are precompiled and the query plan is created only once irrespective of how many times you are executing that query.


2 Answers

I prefer prepared statements in terms of security rather than performance (not sure if it is faster) for example to avoid sql injection.

like image 123
Mike Johnson Avatar answered Oct 23 '22 23:10

Mike Johnson


INSERTs are most likely IO-bound, since they're generally not very complex in terms of SQL - just a list of columns and data to put in them. Thus, what you use to perform the queries isn't as significant in the run time as the amount of data that you're stuffing into the database, how fast you can get the data to the DB server, and how fast the DB server can store it.

like image 1
Amber Avatar answered Oct 23 '22 23:10

Amber