


The performance of require_once is actually very low_PHP tutorial
After testing, require_once is a syntax structure with low performance. Of course, this low performance is relative to require. This article explains the require method currently used in our project and proves its efficiency through experimental code. At the same time , describe the problems we encountered during use, and avoid others stumbling on the same stone.
- require: Introduce a file and compile and import it at runtime.
- require_once: The function is equivalent to require, except that when this file is referenced, it will no longer be compiled and imported.
The above is the difference between the two. It can be seen that the only difference between the two is that require_once has a mechanism to determine whether it has been referenced. Through Internet searches, you can see a lot of data about the performance of require_once being much lower than require. This experiment will not be done here.
The approach in our project is: Define a global variable at the beginning of each file. When require, use isset($xxxxxx) or require 'xxxxx.php';
What are the disadvantages of this approach?
When a global variable is defined in $xxx, if the file is required within the function, the variable will be parsed as a local variable of the function instead of global. Therefore, isset($xxx) or require inside the function The syntactic structure of 'xxx.php' will be invalid, and the results will be unexpected, such as class redefinition, method redefinition, etc.
Learning from the past, so to define global variables, please use $GLOBALS['xxx']. When requiring, use isset($GLOBALS['xxx']) or require 'xxx.php';. Using GLOBALS will be better than Direct definition is a little slower, but it's much better than being wrong.
Since our previous global variables were directly defined, during the discussion with colleagues today, another way of writing came to mind:
The defined position is still defined directly using the $xxx method, and modified in the require method (the global variables defined in the file header are related to the file name).
function ud_require($xxx) { global $$xxx; isset($$xxx) or require $xxx . '.php'; }
This method uses dynamic variables. Compared with the direct GLOBALS method, it has two significant disadvantages:
- Performance, due to the introduction of dynamic variables, is about 2 times slower than the GLOBALS method.
- The indirect reference problem cannot be solved because we cannot predict the file name that is indirectly referenced, and we cannot use global to declare the marked global variables defined in the indirectly referenced files.
Okay, here is my test of require and require_once in GLOBALS method:
require_requireonce.php
<?php function test1($filename) { //pathinfo($filename); isset($filename) or require $filename; } function test2() { require_once 'require_requireonce_requireonce.php'; } $start = microtime(true); while($i ++ < 1000000) isset($GLOBALS['require_requireonce_require.php']) or require 'require_requireonce_require.php'; $end = microtime(true); echo "不使用方法的isset or require方式: " . ($end - $start) . "<br />/n"; $start = microtime(true); while($j ++ < 1000000) test1('require_requireonce_require.php'); $end = microtime(true); echo "使用方法的isset or require方式: " . ($end - $start) . "<br />/n"; $start = microtime(true); while($k ++ < 1000000) test2(); $end = microtime(true); echo "require_once方式: " . ($end - $start) . "<br />/n"; ?>
require_requireonce_require.php (introduced file used to test require)
<?php $GLOBALS['require_requireonce_require.php'] = 1; class T1 {} ?>
require_requireonce_requireonce.php (introduced file used to test require_once)
<?php class T2 {} ?>
The following are the test results (unit: seconds):
- Isset or require method without using method: 0.22953701019287
- Use isset or require method: 0.23866105079651
- require_once method: 2.3119640350342
It can be seen that the require speed without a method is slightly faster than that using the method. Both speeds are about 10 times that of require_once.
So, where is the performance loss?
In the test1 method in the require_requireone.php file above, I commented pathinfo($filename), because my original intention was to use the file name without a suffix as a marked global variable name, but when I use After pathinfo, I found that the performance consumption of this method is basically the same as require_once. Therefore, I added a separate call to pathinfo there and did a test. Sure enough, pathinfo was causing trouble. Therefore, I later modified it to the current version and directly used the file name as the variable name. If you are afraid of duplicate file names, you might as well add the path name...
Guess: After adding pathinfo, the performance consumption of require and require_once is basically the same. So can we guess that PHP's internal processing of require_once is based on it? It is said that require_once has been significantly optimized in PHP5.3. However, I used the PHP5.3.5 version during the test, and I can still see the obvious gap with require. Is it just a larger optimization than the previous version? This has not been tested yet....
Try to modify the test1 method as follows: isset($GLOBALS[substr($filename, 0, strlen($filename) - 4)]) or require $filename;
Use manual string interception. Of course, interception is time-consuming, but it is better than the pathinfo version. The test result this time is:
- Isset or require method without using method: 0.21035599708557
- Use isset or require method: 0.92985796928406
- require_once method: 2.3799331188202
When changing require_once to isset or require mode, you need to pay attention to the following aspects:
- Each file header defines a unique tag variable, defined using $GLOBALS['XXX'] = 1;, and it is recommended that the variable name be the file name or a file name with a path (if a separate file Famous party repeats)
- Define a custom require method:
function ud_require_once($filename) { isset($GLOBALS[$filename]) or require $filename; }

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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.

Dreamweaver Mac version
Visual web development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools
