search
HomeBackend DevelopmentPHP TutorialPHP中使用hidef扩展代替define提高性能_php技巧

网站需要新加一个常量,打开了本地的config.php文件,想到了几年前测试过的hidef以及apc提升define性能的方案。
我的程序中有对开发、测试、生产服务器分别做了不同的配置,在常量方面则使用了一个数组定义了所有需要定义的常量,然后检测是否有apc_load_constants函数,没有的话,批量define。使用apc时,每增加一个常量,还需要修改一下$key才能生效。

而现在测试、生产服务器php都升级到5.4后,opcode缓存就使用了Zend opcache,不再安装APC。因为有用到apc user cache,因此额外装了apcu,和apc用法一模样,完全不用改程序。而apcu不支持apc_load_constants和apc_define_constants,因此apc这个方案就无法用了。去官网装了最新版hidef 0.1.13,2012-7-12发布的stable,一年多了。

写了个简单程序测试define化的时间,大概运行1000次需要2.8ms。那么对于一个中型网站(例如一天php运行1000w次)来说,如果每页定义25个常量,大概每天需要化 10000000*25/1000*2.8=700000ms,就是700秒。差不多使用hidef可以一天节省700s的PHP运行时间。
再看看读的性能好了,测试读1w次一个常量,值都是1,分别是37ms和0.7ms。那么如果一天1000w次,每页平均使用20个常量,则需要740秒,而使用hidef是14秒,好吧,又一个700多秒。
一天省1400秒php运行时间,也许是还是微不足道,但总是好的,也是值的尝试的,毕竟define的参数变化的机率非常少。
当define参数需要修改时,修改配置文件,然后重载下php-fpm,就好了。

hidef具体安装方法参见:提高define性能的php扩展hidef的安装和使用

在百度里搜索“hidef”,排第3位的是一个copy我博文的网站:( 而我自己发布的提高define性能的php扩展hidef的安装和使用在前三页没有找到。显然是百度对原创的识别出了些偏差。

百度搜索“hidef php”,那个网址排第一,第二是官网,我的在第三。
gg搜索“hidef php”,第一官网,第3是另一篇原创,我的在第四。gg的识别就不错!

360搜索"hidef php",第一那个copy站,第二我的,第三另一篇原创。
因此有了这篇的诞生,看看能不能帮第一篇排上去或者这篇排上去也行。


附原配置常量的程序示例代码:

复制代码 代码如下:

  if (function_exists('apc_load_constants')) {
            function define_array($key, $arr, $case_sensitive = false) {
                if (!apc_load_constants($key, $case_sensitive)) {
                    apc_define_constants($key, $arr, $case_sensitive);
                }

            }
        } else {
            function define_array($key, $arr, $case_sensitive = false) {
                foreach ($arr as $name => $value) {
                    define($name, $value, $case_sensitive);
                }
            }
        }

        $constants = array(
            'HX'   => 1,
            'BLOG_URL'   => 'http://www.jb51.net/',
            'WWW_URL'   => 'http://www.jb51.net/',
        );

        define_array('hx_defined',$constants);


附测试define速度的代码。

复制代码 代码如下:

$t1 = microtime(1);

    $constants = array(
        'hx1'       => 1,
        'hx2'       => '2',
        'hx3'       => '3',
        'hx4'       => '4',
        'hx5'       => '5',
        'hx6'       => '6',
        'hx7'       => '7',
        'hx8'       => '8',
        'hx9'       => '9',
        'hx10'       => '10',
    );

    function define_array($key, $arr) {
        foreach ($arr as $name => $value) {
            define($name.$i, $value);
        }
    }
   
    for($i=0;$i         define_array($i,$constants);
    }
   
   
$t2 = microtime(1);
echo ($t2-$t1)*1000;

//读性能
$t1 = microtime(1);
for($i=0;$i     $t = hx1;
}   
$t2 = microtime(1);
echo ' '.($t2-$t1)*1000;

$t1 = microtime(1);
for($i=0;$i     $t = HX;
}   
$t2 = microtime(1);
echo ' '.($t2-$t1)*1000;

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)