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.
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.