Archive for the ‘php’ Category
Static call versus Singleton call in PHP
Introduction
In the past several months I’ve been working with a rather large application built with symfony. I noticed that symfony makes heavy use of the Singleton pattern (other frameworks, like Zend do that too); everywhere in the code there were pieces like this one:
<?php
// ...
sfSomething::getInstance();
// ...
?>
I know that in more than half of the situations, you can write your code using plain static classes, with some initialize() method, as an alternative to writing singletons. For example, this is a dummy Singleton:
<?php
class DummySingleton {
private function __construct(){}
private function __clone(){}
public static function getInstance(){
if(self::$__instance == NULL) self::$__instance = new DummySingleton;
return self::$__instance;
}
public function foo(){
echo 'I am DummySingleton::foo()';
}
}
?>
Now this is a completely useless class, but it suits our purpose of illustrating the Singleton. Notice the amount of code needed by the Singleton pattern. Except the foo() method, all the code in the class makes sure you have only one instance at any time during the execution.
Now let’s write a static class that does the same thing as the Singleton:
<?php
class DummyStatic {
static public function foo(){
echo 'I am DummyStatic::foo()';
}
}
?>
This is much cleaner, as we don’t need the extra code the Singleton needs, and can focus on our task at hand.
Performance comparison
Let’s compare the performance of the two approaches. I’ve written a small test script that looks like this:
<?php
/**
* A singleton class
*/
class TestSingleton {
// singleton code
private static $__instance = NULL;
private function __construct(){}
private function __clone(){}
static public function getInstance(){
if(self::$__instance == NULL) self::$__instance = new TestSingleton;
return self::$__instance;
}
// our actual code
public $val = 0;
public function test(){
for($i=0;$i<30;$i++) $this->val += $i;
}
}
/**
* a plain static class (all members are static)
*/
class TestStatic {
static public $val = 0;
static public function test(){
for($i=0;$i<30;$i++) self::$val += $i;
}
}
// how many runs
$runs = 500000;
// benchmarking Singleton
$start = microtime(TRUE);
for($i=0;$i<$runs;$i++) TestSingleton::getInstance()->test();
$run1 = microtime(TRUE) - $start;
// benchmarking static $start = microtime(TRUE); for($i=0;$i<$runs;$i++) TestStatic::test(); $run2 = microtime(TRUE) - $start; echo '<pre>'; echo 'test singleton: '.number_format($run1, 8)." s\n"; echo 'test static: '.number_format($run2, 8).' s'; ?>
Basicly, I put together the two types of classes. Both have a method called test(), which does some arithmetic operations, just to have something that spends some execution time.
I’ve ran this script for various values for the $runs variable: 100, 1k 10k, 100k, 200k, 300k, 500k and 1M.
Test results
Number of runs | Singleton call time (s) | Static call time (s) |
100 | 0.004005 | 0.001511 |
1,000 | 0.018872 | 0.014552 |
10,000 | 0.174744 | 0.141820 |
100,000 | 1.643465 | 1.431564 |
200,000 | 3.277334 | 2.812432 |
300,000 | 5.079388 | 4.419048 |
500,000 | 8.086555 | 6.841494 |
1,000,000 | 16.189018 | 13.696728 |
I have also done some spreadsheet magic, and generated this chart:
As you can see, for a relatively small number of runs (<1k), the Static code is significantly faster than the Singleton, an than it stabilizes arround 15% faster than Singleton, as I expected. This is because every function/method call involves some operations (symbol lookup, stack manipulation etc.), and each call to the Singleton method, in fact, also calls the getInstance() static method.
Conclusion
It may not be that obvious that making extensive use of Singletons has this kind of side effect; however, if your code has more that 100 or 1,000 calls to some getInstance() method of a Singleton class, you might want to consider caching the reference to the object it returns, or even refactoring the code to use only static method calls.
You might say that you need an object because you do stuff in the constructor. That can be easily achieved with some kind of static initialize() method, that should be called once in your code, just before usage. If you have some auto loading mechanism in place, you could call it just after loading the class, for example, if you want to automate the initialization process. But keep in mind that this is not a 100% replacement for Singletons; you need an object if you want to serialize/unserialize it (for caching, some RPC call, etc.).
Update.
Tested with Facebook’s HPHP compiler:
I’ve tested the script using the HPHP compiler, and the results are spectacular. While keeping the same time ratio between the Singleton and Static calls, what stroke me is the huge difference (HPHP is ~ 200 times faster):
Number of calls | Time spent (Apache) | Time spent (HPHP) | ||
Apache Singleton call | Apache Static call | HPHP Singleton call | HPHP Static call | |
100 | 0.004005 | 0.001511 | 0.00001502 | 0.00000906 |
1,000 | 0.018872 | 0.014552 | 0.00008988 | 0.00007486 |
10,000 | 0.174744 | 0.141820 | 0.00075102 | 0.00063801 |
100,000 | 1.643465 | 1.431564 | 0.00829983 | 0.00795388 |
200,000 | 3.277334 | 2.812432 | 0.01839614 | 0.01339102 |
300,000 | 5.079388 | 4.419048 | 0.02502608 | 0.01932502 |
500,000 | 8.086555 | 6.841494 | 0.04114008 | 0.03280401 |
1,000,000 | 16.189018 | 13.696728 | 0.07872796 | 0.06373119 |
Happy coding.
Apache 2 PHP module version switcher for Debian/Ubuntu (2)
Hello again,
I decided to continue my little experiment with PHP and Apache 2, and installed PHP 5.3.0, so that I could enjoy thinks like closures, namespaces and so on, without having to cope with PHP6’s state of development and with it’s bugs. I compiled it from source, using this command:
./configure --with-apxs2=/usr/bin/apxs2 --with-mysql --prefix=/opt/php53 --with-regex --with-libxml-dir=/usr/lib --with-openssl=/usr/lib --with-pcre-regex --with-curl --enable-exif --with-gd --enable-gd-native-ttf --with-gettext --with-mhash --with-imap --with-imap-ssl --enable-mbstring --with-mcrypt --with-mssql --with-mysql --with-mysqli --enable-pcntl --with-pspell --with-libedit --enable-shmop --enable-soap --enable-sockets --enable-sysvmsg --enable-sysvsem --enable-sysvshm --with-tidy --with-xmlrpc --with-xsl --with-openssl=/usr --with-kerberos --enable-embedded-mysqli=shared --with-pdo-mysql=shared --enable-shared=yes --with-interbase=no --with-oci8=no --with-adabas=no --with-pdo-firebird=no --with-pdo-oci=no --with-pdo-odbc=no --with-pgsql=no --with-pdo-mysql --with-pdo-pgsql=no --with-recode=no --with-snmp=no --with-sybase-ct=no
Later edit:
After that run make. Before running sudo make install, please backup the /usr/lib/apache2/modules/libphp5.so file, because it will get overwritten by the install command. After running make install, rename the /usr/lib/apache2/mobules/libphp5.so file to libphp53.so, and copy back the backuped version of libphp5.so.
After that, I created the php53.load and php53.conf files in the /etc/apache2/mods-available/ folder (copy the contents of php5.conf and php5.load and modify the LoadModule directive to include libphp53.so instead of libphp5.so), and updated my shell script to consider this version too. Also, so it happend that I was reading some RSS feeds about some changes in Ubuntu 9.10 (Karmic Koala), and decided to add some eye candy to the script, that is notify-osd. Notify-osd is the program that makes those nice notification bubbles that was introduced in Ubuntu 9.04. I installed the libnotify-bin package, played a little and came up with this version of the apapche-php script:
#!/bin/bash
php5="/etc/apache2/mods-enabled/php5.load"
php53="/etc/apache2/mods-enabled/php53.load"
php6="/etc/apache2/mods-enabled/php6.load"
apache="/var/run/apache2.pid"
old=""
if [ -e "$php5" ]
then
old="php5"
enabled5="TRUE"
else
enabled5="FALSE"
fi
if [ -e "$php53" ]
then
old="php53"
enabled53="TRUE"
else
enabled53="FALSE"
fi
if [ -e "$php6" ]
then
old="php6"
enabled6="TRUE"
else
enabled6="FALSE"
fi
if [ -e "$apache" ]
then
running="started"
op="/etc/init.d/apache2 restart"
else
running="stopped"
op="/etc/init.d/apache2 start"
fi
echo "5$enabled5"
echo "6$enabled6"
run=$(zenity --title "Switch PHP version" --list \
--text "Apache ($running) with PHP 5/6" --radiolist\
--column "Active" --column "run" --column "Version" --hide-column=2 \
"$enabled5" "php5" "Apache 2 with PHP 5.2.10" \
"$enabled53" "php53" "Apache 2 with PHP 5.3.0" \
"$enabled6" "php6" "Apache 2 with PHP 6-DEV" \
);
if [ -z $run ]
then
exit
fi
if [ $run != $old ]
then
a2enmod $run
a2dismod $old
fi
$op | zenity --progress --pulsate --auto-kill --auto-close --title "Applying changes ...."
sleep 1
phpversion=""
if [ "php5" == "$run" ]
then
phpversion="5.2.10"
else
if [ "php53" == "$run" ]
then
phpversion="5.3.0"
else
if [ "php6" == "$run" ]
then
phpversion="6.0.0-DEV"
fi
fi
fi
if [ -e "$apache" ]
then
notify-send "Apache 2 with PHP $phpversion" "Changes applied and server restarted succesfully" -i dialog-info -u normal
#zenity --info --text "Changes applied"
else
notify-send "Apache 2" "An error occured, please check the Apache log file for details" -i dialog-error -u critical
#zenity --error --text "An error occured, check the apache log"
fi
When you run this (with gksudo of course), it displays this list:
After checking the version you want, it will display a progress dialog, wait one second and then, the notification daemon will display this bubble on success:
… or this one on failure:
Enjoy !
Apache 2 PHP module version switcher for Debian/Ubuntu
Update, see the part 2, also starring PHP 5.3 !
One of these days I thought of trying out a snapshot of the current development version of PHP‘s next major version, PHP 6. I’m using an alpha version of Ubuntu (Karmik alpha3), which behaves very nicely, and I thought to go all the way with this and try a dev version of PHP.
After installing some of the dependencies needed to compile PHP (dev versions of various system libraries and build tools), and tying without any luck to compile a tar.gz snapshot of PHP 6, I checked out the sources from SVN, and got it working. After much trial and error, I succeeded using this configure command:
./configure --with-apxs2=/usr/bin/apxs2 --with-mysql --prefix=/opt/php6 --with-regex --with-libxml-dir=/usr/lib --with-openssl=/usr/lib --with-pcre-regex --with-curl --enable-exif --with-gd --enable-gd-native-ttf --with-gettext --with-mhash --with-imap --with-imap-ssl --enable-mbstring --with-mcrypt --with-mssql --with-mysql --with-mysqli --enable-pcntl --with-pspell --with-libedit --with-readline --enable-shmop --enable-soap --enable-sockets --enable-sysvmsg --enable-sysvsem --enable-sysvshm --with-tidy --with-xmlrpc --with-xsl --with-openssl=/usr --with-kerberos --enable-embedded-mysqli=shared --with-pdo-mysql=shared --enable-shared=yes --with-fbsql=no --with-interbase=no --with-oci8=no --with-adabas=no --with-pdo-firebird=no --with-pdo-oci=no --with-pdo-odbc=no --with-pgsql=no --with-pdo-pgsql=no --with-recode=no --with-snmp=no --with-sybase-ct=no --enable-debug
After that, make and sudo make install. During the make install command, the script complained about httpd.conf not containig any LoadModule section. In Debian and Debian based distros, like Ubuntu, the Apache settings are split over multiple files. Every apache module has a .conf and a .load file in /etc/apache2/mods-available.
The .load file contains the specific LoadModule directive, and the .conf file contains module specific configurations. The reason for this is to make it simpler to activate/deactivate a specific module using the a2enmod and a2dismod commands, which create or destroy symlinks for the .conf and .load files from /etc/apache2/mods-available to /etc/apache2/mods-enabled. During Apache’s startup, it loads any .load files in the mods-available folder, then it loads any .conf files in the same folder.
I added a dummy LoadModule line in httpd.conf, and ran make install again. After that I took the LoadModule line injected by the install script into httpd.conf and put it in a file called php6.load in the mods-available folder, and reverted httpd.conf to the initial state (an empty file). Also I created a php.ini file in /opt/php6/lib/.
Then I disabled the php5 module with
sudo a2dismod php5 && sudo a2enmode php6 && sudo /etc/init.d/apache2 restart
and tested a phpinfo page. It worked 🙂 and I was happy.
But as I tested some of my apps in PHP6, I ran into some trouble and wrote this little script to help me easily switch between PHP versions to use when I’m researching or when I’m working. It uses a little program called zenity, which display all sorts of configurable GUI elements on the screen. Here it is:
#!/bin/bash php5="/etc/apache2/mods-enabled/php5.load" php6="/etc/apache2/mods-enabled/php6.load" apache="/var/run/apache2.pid" old="" if [ -e "$php5" ] then old="php5" enabled5="TRUE" else enabled5="FALSE" fi if [ -e "$php6" ] then old="php6" enabled6="TRUE" else enabled6="FALSE" fi if [ -e "$apache" ] then running="started" op="/etc/init.d/apache2 restart" else running="stopped" op="/etc/init.d/apache2 start" fi run=$(zenity --title "Switch PHP version" --list --text "Apache ($running) with PHP 5/6" --radiolist \ --column "Active" --column "run" --column "Version" --hide-column=2 \ "$enabled5" "php5" "Apache with PHP 5" \ "$enabled6" "php6" "Apache with PHP 6-DEV" \ ); if [ -z $run ] then exit fi if [ $run != $old ] then a2enmod $run a2dismod $old fi $op | zenity --progress --pulsate --auto-kill --auto-close --title "Applying changes ...." sleep 1 if [ -e "$apache" ] then zenity --info --text "Changes applied" else
zenity --error --text "An error occured, check the apache log" fi
I put this one in /opt/bin (this is the place where I put experimental stuff ) and called it apache-php (had a lack of imagination on the name). I also made a shortcut with a nice icon, so I can access it easily. Please note that you must run the script with gksudo, eg. “gksudo /opt/bin/apache-php”, because you need to be root to modify any settings in the /etc folder (or any system folder for that matter).
What this script does, is this; it looks for the php5.load and php6.load files in the mods-enabled folder, and displays a nice zenity dialog with the one enabled already selected, like the one in this picture
After selecting the desired PHP version, and you hit OK, a progress dialog appears for a short while, while the changes are being made:
and then, on completion a simple alert that informs of the completion of the process:
The script waits for Apache to restart, then waits one second and the checks for the Apache pid file ( /var/run/apache2.pid ). If the file is not there, it means that something went wrong, and an error box like this one is displayed;
Usually this should not happend, but if it does, something went wrong, and you have to check the Apache logs to find it.
I know that there are methods for running PHP5 and PHP6 in the same time, one as an Apache module and the other as FastCGI, but it adds unneeded complexity, and you can’t use the same file extension with both, which, in my humble oppinion, is not the proper way to use and test PHP6.
I hope this helps people who use different versions of PHP and like to switch version with a click. With a little imagination and tweaking, you could transform this script into a more complex one, for, let’s say enable and disable different Apache modules, or add more PHP versions, etc.
I encourage you to compile PHP 6 and try it, and report bugs back to the development team, because, besides letting them know that you’re interested in their work, you help them find bugs and fix them. Also, check this page for progress in the Unicode compatibility of different PHP functions and extensions.
Happy coding and compiling folks.