简体   繁体   English

打开一个MySQL连接与打开和关闭许多连接?

[英]Opening one MySQL connection vs opening and closing a lot of connections?

I have a > x20000 loop in php that checks if an entry exists in a MySQL database, I open & close the connection for every entry in the loop, but a friend told me that's crazy and I should open one connection, run the loop and then close it, but he didn't tell me why. 我在php中有一个> x20000循环,用于检查MySQL数据库中是否存在某个条目,我为循环中的每个条目打开和关闭连接,但是一个朋友告诉我这很疯狂,我应该打开一个连接,运行该循环并然后关闭它,但他没有告诉我原因。 Could someone explain me the benefits of reusing the same connection? 有人可以向我解释重用同一连接的好处吗? is it CPU usage or what? 是CPU使用率还是什么?

It is the network connection + mysql connection overheads. 它是网络连接+ mysql连接的开销。 It takes a time to connect and to be clear it is "expensive" operation. 连接需要花费一些时间,并且很显然这是“昂贵的”操作。

Not only is it expensive, but if you have multiple requests coming in for the script that are doing it simultaneously, you could end up bumping up against the connection limit on the server, such that further requests must wait or are denied. 这不仅很昂贵,而且如果同时有多个请求同时执行该脚本,则最终可能会超出服务器的连接限制,以致其他请求必须等待或被拒绝。

But the main thing, as @zerkms said, is that it's an expensive operation. 但是,正如@zerkms所说的,最主要的是这是一个昂贵的操作。 About six months ago, I took a script that made repeated connections in a loop and moved the connection outside the loop, and the script's execution time dropped from 10-12 seconds to well under 1 second. 大约六个月前,我使用了一个脚本,该脚本在循环中重复进行连接,并将连接移到循环外,脚本的执行时间从10-12秒减少到不到1秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM