doutuan4361 2015-03-22 07:42
浏览 80
已采纳

使用PHP会更快:多个DB连接类实例还是单例?

I am working a new PHP project that calls upon a records class to update the database. Currently every object or script that needs to do so makes a new instance of the object. In theory this could mean as many as six or seven instances per call.

The design currently calls for the object to connect to the database in the constructor method which would mean between 0 and 7 connections?

For the demo I will be using only MySQL but as it is all tucked away behind a single interface one imagines that it could easily be ported to other data stores (and probably will).

Given the nature of the project speed of response is the key optimisation point however with so many connections do I run the risk of overloading the system when demand is high and therefore slowing everything down anyway?

Is this a situation when it would simply be better (and faster overall) to use a singleton?

Or is there some way to have my cake and eat it?

  • 写回答

3条回答 默认 最新

  • duanmaifu3428 2015-03-22 07:59
    关注

    A connection to a database server takes time to connect and will consume memory. Also the number of connections a database server will accept at the same time is limited. That's why the number of connections should be kept as small as possible which means that only a single connection to the same database should be used.

    Using just a single connection means not that you have to use the Singleton pattern. Simply create the connection object somewhere at the start of the script and pass it to components which will execute DB queries.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部