Under the cut, the translation of the rather old post of Fabien (Fabien Potencier) on the subject of print vs echo, is remarkable, in my opinion, by the method of establishing “truth”. Unlike the vast majority of such studies, you will not find the launch of scripts with echo and print millions of times in this.
Disclaimer: the translation is not literally literal as well as literary.print vs echo, which one is faster?
Like most of us, I'm tired of reading blog posts about pointless micro-optimizations like replacing print with echo, ++ $ I with $ i ++ or double quotes with single quotes. Why? Because in 99.999999% of cases, it does not matter. Why? Because in 99.99% of cases it would be better on your part if you installed an OPC type opcode cache, or added indexes missing from your database, or tried not to make the 1000 SQL queries that you have on the main one.
But let's pretend that you really want to know the answer to this question. Instead of trying to write a script and run it millions of times, I want to show you a tool that can be useful in that it helps to better understand our php code.
')
Meet -
VLD - "Vulcan Logic Disassembler". The VLD is written by
Derrick Rethans and, as it becomes clear when reading the main page of the project, "VLD clings to the Zend Engine and dumps all the opcodes of the script being executed."
Installing VLD is trivial - download and install just like any other php extension.
phpize $ ./configure $ sudo make install
Connect the extension to php.ini
extension=vld.so
(well, or in some sort of /etc/php/apache2/conf.d/vld.ini - you know better where it is more correct to do this in your OS).Time to look under the hood. Create two files: one with echo and the other with print.
Run these scripts from the command line with the -d vld.activate = 1 parameters to activate the VLD output and let's look at the opcode issued by the scripts.
$ php -d vld.active=1 print.php
number of ops: 4 compiled vars: none line
-
$ php -d vld.active=1 echo.php
number of ops: 3 compiled vars: none line
Found a difference? - Yes, print uses one opcode more, because it returns something. We can conclude that echo is faster than print. But one opcode is worth nothing. True. Even if the script has hundreds of calls to print (remember the formula X = E-1 approx. Lane.)
By the way, due to the fact that print always returns 1, you can do interesting things like this:
Do you want to know the number of opcodes performed when running a script with a bunch of inclusions? Try this:
$ php -d vld.active=1 print.php 2> output $ grep "number of ops" output | cut -f 5 -d ' ' | (tr '\n' +; echo 0) | bc
I tried on bare wordpress. On my laptop, the script hangs until it crashes with an error "Bus Error", but by this time the number of opcodes exceeds 2.3 million. That says it all.