doutuan4361
2015-03-22 15: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 duanmaifu3428 2015-03-22 15: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.

    点赞 评论 复制链接分享
  • dongyouzhi7218 dongyouzhi7218 2015-03-22 16:01

    I can suggest you two solutions:

    1. Use stored procedure if you can, it will decrease # of Mysql connections, its more safety, and its cached.

    2. Use at first time Mysql connection and than save data into Redis or Memcached.

    It intend to your queries and your needs.

    Thanks

    点赞 评论 复制链接分享
  • drug95107 drug95107 2015-06-22 11:37

    Look at this solution. It uses singleton approach for each connection and handles multiple connections across multiple adapters (e.g. mysql, memcached etc.)

    点赞 评论 复制链接分享

相关推荐