This article references: http://blog.csdn.net/taft/article/details/596291
If you have not written PHP extensions and are a geek of performance, then this article is definitely for you:
If you have such a PHP program
function Self_concat ($string, $n) { $result = ""; for ($i = 0; $i < $n; $i + +) { $result. = $string; } return $result;} $str = Self_concat (' Fire ', 10);
If the second parameter passed in is large, what is the program's performance? I test on my own machine if n=10000000 time is about 0.6s, if I write this PHP function in C and then PHP calls directly, will it be fast? Then start writing a simple extension that is statically compiled into a. So way to load, and I explain it in the quickest and most concise way.
1. First you need to have PHP source directory CD to its ext directory to execute:
./ext_skel--extname=luckyext--proto=luckyext.def
This command will automatically generate a directory called Luckyext has a basic extension skeleton file, the core of the file only three congif.m4 used to do the compilation configuration, luckyext.h definition of the file includes declaring your custom function, There are luckyext.c used to write C's function source code, the others are additional skeleton files, temporarily can not tube.
2. Write the function you want in luckyext.c, remember to declare it in the header file, or you will get an error when compiling.
3. Compiling extensions about PHP environment configuration don't say it.
Phpize./configuremake&&make Install
A successful compilation will generate a luckyext.so file in your PHP-specified extension directory.
4. Introducing an extension to reload PHP
Vi/etc/php.iniextension=luckyext.so
I am a Mac machine, please look at the configuration of your machine when modifying, save restart FPM when finished
Killall PHP-FPMPHP-FPM
5. Testing
Terminal input
Php-m
Out of the extension should have luckyext, as to what it supports function can be used in the Ext/luckyext directory luckyext.php script to run to see the normal situation will output its supported functions Self_concat_c ()
6. Performance comparison directly run C-write PHP
!--? phpself_concat_c (' Fire ', 10000000); The result of the
is amazing, 0.06 seconds, 10 times times the difference! Why, because if PHP that set of code, every time to the string plug character, PHP needs to do a dynamic allocation of memory, the more cycles, the greater the performance overhead, and C write the function directly on the calculation of the final need to allocate how much memory, so quickly here, is not very interesting ~ haha , at least I feel very exciting!
The c example of this article is a reference to the predecessor of the translation of the document, after more than a revision of C's foundation, I will study more C knowledge, refueling!