php - PDO/PHP/MySQL 中的性能 : transaction versus direct execution

标签 php sql mysql transactions pdo

我循环遍历多个值(例如 1 到 100)并在循环内执行准备好的语句。

与在循环内直接执行相比,使用事务(在循环结束后提交)是否有优势?

这些值彼此不依赖,因此从这个角度来看不需要交易。

最佳答案

如果您的查询是 INSERT,页面 7.2.19. Speed of INSERT Statements MySQL 手册的一部分提供了两个有趣的信息,具体取决于您是否使用事务引擎:

使用非事务引擎时:

To speed up INSERT operations that are performed with multiple statements for nontransactional tables, lock your tables.

This benefits performance because the index buffer is flushed to disk only once, after all INSERT statements have completed. Normally, there would be as many index buffer flushes as there are INSERT statements. Explicit locking statements are not needed if you can insert all rows with a single INSERT.

并且,使用事务引擎:

To obtain faster insertions for transactional tables, you should use START TRANSACTION and COMMIT instead of LOCK TABLES.

所以我猜测使用事务可能是个好主意——但我想这可能取决于您服务器上的负载,以及是否有多个用户同时使用同一个表,以及所有这些......

我链接到的页面上有更多信息,所以不要犹豫,阅读它;-)


而且,如果你正在做 update statements :

Another way to get fast updates is to delay updates and then do many updates in a row later. Performing multiple updates together is much quicker than doing one at a time if you lock the table.

所以,我猜对于插入来说也是如此。


顺便说一句:可以肯定的是,您可以尝试这两种解决方案,并使用 microtime 对它们进行基准测试, 例如在 PHP 方面 ;-)

关于php - PDO/PHP/MySQL 中的性能 : transaction versus direct execution,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1415602/

相关文章:

java - 从 mybatis select 获取不同 java 对象的多个值

sql - 从函数 postgresql 输出到屏幕并记录文件

mysql - MySQL 中何时使用单引号、双引号和反引号

php - 字符串 "ďťż"随机出现在我的页面上,但只出现在 firefox 中。 IE和chrome没有这个问题。

php - Laravel 4 使用数据从 Controller 向外部 URL 发出发布请求

php - 执行后更改php文件

javascript - 在 javascript animate 中使用 asp.net VB 变量

mysql - 查询选择记录

mysql - 获取某一年每小时的订单数

php - 使用 PHP 解析实时 SOAP 数据流