2

I would like to ask about the performance and memory usage of instantiating an object in php.

On every php file of my application, i included a file which connect to the database.

$db->DB::getInstance();
$db->connect('all my credentials');

This is the getInstance() function in my db class.

//singleton database instance
public static function getInstance() {
    if (!self::$Instance) {
        self::$Instance = new DB();
    }

    return self::$Instance;
}

Currently everything turns out well. But i am concern of performance issues as in, can it be improved, possbile flaws etc.

I researched and found out that singleton instance can help to save memory. It will reuse the object if it's already been instantiate. Am i right?

My exact question is

E.g. if i have 10 users accessing the script, does it means that the object will be instantiate 10 times? When that happens, will it put 10 x load on my memory usage? -> this is pretty what i am interested in

Appreciate any expert advice.

Slay
  • 1,285
  • 4
  • 20
  • 44
  • *(related)* [Who needs Singletons](http://stackoverflow.com/a/4596323/208809) – Gordon May 07 '12 at 07:56
  • However using the same instance may prevent creating new connections if it is a `mysqli` class. It depends on what your class constructor is doing. But anyway it has nothing to do with creating the object itself. – SOFe May 05 '19 at 12:15

2 Answers2

7

As with all performance tweaking, you should measure what you're doing instead of just blindly performing some voodoo rituals that you don't fully understand. When you save an object in $_SESSION, PHP will capture the objects state and generate a file from it (serialization). Upon the next request, PHP will then create a new object and re-populate it with this state. This process is much more expensive than just creating the object, since PHP will have to make disk I/O and then parse the serialized data. This has to happen both on read and write.

In general, PHP is designed as a shared-nothing architecture. This has its pros and its cons, but trying to somehow sidestep it, is usually not a very good idea.

NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
  • I'm the same opinion. Don't try to tweak stuff at the wrong spot. Using a singleton instance or not doesn't matter in this case. But yes, your objects are always created seperate to each request. I mean, how else should that happen, PHP is a scripting language. – Johannes Klauß May 07 '12 at 07:47
  • Actually, using Sessions is not bad. Session writing and reading is a very fast process (on any decent server, reading and writing files is just about the fastest non-PHP-only operation you can do). It's often faster than database requests and most modern frameworks rely highly on file read/write for sessions, cache and other purposes. So as a developer, you should not be afraid of file read/writes. – kingmaple May 07 '12 at 07:51
  • @kristovaher its not a matter of being afraid than a matter of being aware that disk i/o is slow. – Gordon May 07 '12 at 07:55
  • Thank you alot, i will take a look at using sessions. – Slay May 07 '12 at 07:56
  • @Gordon Unless your website is static, you will be using disk i/o anyway. Even database queries are disk i/o, including files and pretty much majority of things your PHP script does. What is important, when using sessions, is to session_start() only if you need to. Never session_start() for every request, since it does carry a small performance hit (not just because of disk read/write, but also because of headers). Sessions should only be started if session data is requested or written. – kingmaple May 07 '12 at 08:02
2

Do not use Singleton's, it makes testing a hell.

Objects are sent around the system in PHP as references by default. So you can simply share that Database connection object around other classes in the system without performance hit (it won't clone them until you specifically order it to be cloned).

But yes, if ten users use your system then that means you will have ten instances of that class. And it means that memory usage is ten times higher IF all the requests of users are active at the same time (well, usually, depending on load and server settings, some requests may have to wait until others are complete).

It is possible to tell PHP and database to use persistent connections, which means that other scripts that use the same database username and password and connect to the same database, share the 'connection'. But this is almost never recommended, since requests from one user may slow down the experience of another user who has to wait while the previous users database query has completed.

So, in short, do not use Singletons. In a smart object-oriented architecture, the class is passed to child objects or inherited from parents. This means that the class can easily be changed or a mockup can be easily created for testing purposes.

kingmaple
  • 4,200
  • 5
  • 32
  • 44
  • Singletons are bad, yes. A smarter design pattern would be Singleton factory or any type of Dependency Injection Container. – G. Kashtanov Oct 19 '16 at 08:45
  • 1
    Singletons are not that bad, there are situations when it is better to use them instead of other solutions, for instance NullObject – tino415 Jun 20 '17 at 07:20
  • That's more like caching than singleton. Singleton is usually bad when it becomes a god object. – SOFe May 05 '19 at 12:16