提高define性能的php扩展hidef的安装和使用

yipeiwu_com5年前PHP代码库
官网:http://pecl.php.net/package/hidef
简介:
  Allow definition of user defined constants in simple ini files, which are then processed like internal constants, without any
of the usual performance penalties.
  允许使用简单的ini文件来定义需要的常量,就像使用内部变量一样,而且没有使用Define的性能问题。

作者说Hidef is initialized in php module init, before apache starts spawning children.
在apache启动前,PHP启动时创建并初始化了这些常量,这样就不需要在php里define常量了,性能自然没有任何问题了!
在Nginx下同样可用,以下是安装过程:

1、下载并解压进入目录

# wget http://pecl.php.net/get/hidef-0.1.8.tgz
# tar zxvf hidef-0.1.8.tgz
# cd hidef-0.1.8

2、没有configure文件,执行phpize创建该文件

# /usr/local/webserver/php/bin/phpize
# ./configure --enable-hidef --with-php-config=/usr/local/webserver/php/bin/php-config
# make
# make install

3、添加到php.ini文件里面

# vi /usr/local/webserver/php/etc/php.ini

-----------------------------------------------
extension=hidef.so
hidef.ini_path=/usr/local/webserver/php/etc/
------------------------------------------------------------------------------

注意,如果php.ini文件里面没有定义hidef.ini_path,则默认.ini文件读取位置为/hidef,只需手工创建文件 vi /hidef/hidef.ini即可。

# vi /usr/local/webserver/php/etc/hidef.ini(此处根据情况自己调整路径)
复制代码 代码如下:

[hidef]
int ANSWER = 42;
str HX = "9enjoy";
float PIE = 3.14159;

这里整数用int,浮点数用float,字符串用str。
字符串str的值使用双引号来包含,或者直接写字符串内容。如果使用单引号,将会把单引号也做为字符串的内容。
如str HX='9enjoy',实际存储的不是9enjoy,是'9enjoy'。

4、重新加载php-fpm即可

# /usr/local/webserver/php/sbin/php-fpm reload

此时,查看phpinfo()的结果,在hidef处就可以看到定义的变量。


-----------------------------------------------------------------------------

附:

如果使用了APC,apc提供了定义常量的方法。apc_define_constants和apc_load_constants。apc_define_constants将常量转为数组存到一个user cache中。虽然把常量存在了内存中,但每次PHP请求时,仍然需要读cache,分别定义,因此也不会有什么明显的性能提升。我测试了下定义25个常量,使用apc的函数比直接定义常量快了0.01ms。

这样使用:
if(!apc_load_constants('defined')) {
    $constants = array(
        'HX'   => TRUE,
        'D_BUG' => 1
    );
    apc_define_constants('defined', $constants);
}

define() is notoriously slow. Since the main benefit of APC is to increase the performance of scripts/applications, this mechanism is provided to streamline the process of mass constant definition. However, this function does not perform as well as anticipated.

For a better-performing solution, try the hidef extension from PECL.

APC的文档中推荐使用hidef。

相关文章

php代码运行时间查看类代码分享

复制代码 代码如下: //date:2011-08-05 class RunTime//页面执行时间类 { private $starttime;//页面开始执行时间 private $...

讲解WordPress中用于获取评论模板和搜索表单的PHP函数

comments_template()(获取评论模板) comments_template() 函数用来获取评论模板,一般只能用在文章或者页面上,如果不是文章或者页面将无法显示。 用法...

php调用方法mssql_fetch_row、mssql_fetch_array、mssql_fetch_assoc和mssql_fetch_objcect读取数据的区别

方法名:mssql_fetch_row() 测试: 复制代码 代码如下: require 'dbconn.php'; $sql = 'select * from _Test'; $que...

Laravel实现autoload方法详解

Laravel实现autoload方法详解

用了一阵Laravel后发现很少有include和require,觉得有点奇怪,思考Laravel是怎么完成文件导入的。 其实Laravel依旧还是用include或者require的,...

PHP 配置open_basedir 让各虚拟站点独立运行

当时觉得这跟IIS相比,实在太差了,因为在IIS里,可以在安全性里设置一个站点甚至一个目录访问时使用的匿名账号,只要各个站点使用的账号不一样,站点间的安全就不会互相影响。这几天才发现,原...