开发者

Is it bad to prepare a statement multiple times?

开发者 https://www.devze.com 2023-02-24 03:25 出处:网络
Normally you\'d prepare a statement, and then you\'d only send different values when you开发者_Go百科 execute it inside of loops.

Normally you'd prepare a statement, and then you'd only send different values when you开发者_Go百科 execute it inside of loops.

But I've seen MVC code where the statements are being prepared for every call of the update method, for example. So my question is - does this hurt performance? And if so, by how much? Is it worse or still better than not preparing statements in the first place? Or does PHP and/or MySQL realize it and only prepare it once?


Some databases and application servers do cache prepared statements on the client side and realize that you're trying to prepare a statement that has already been prepared, and serve up the reference to the pstmt from the cache. This is very common in Java app servers, but may not be so common in PHP.

Preparing a statement is certainly more expensive than not. It requires some extra round trips to the database, so it is only worth it, from a performance perspective, if you're going to be calling the same SQL (with different parms) many, many times.

However, there is another aspect beyond performance - security. Prepared statements are the single best line of defense against SQL Injection attacks - which are incredibly prevalent. Because of this, I would always use prepared statements, even if it may be technically more performant to just skip the prepare step in some cases.


I doubt PHP and/or MySQL are that smart. So, AFAIK, it hurts performance, as it makes additional roundtrip to the database, but I doubt you will ever notice that.

0

精彩评论

暂无评论...
验证码 换一张
取 消