| PHPPerformance Optimization:General Introduction:I. Specification Descriptionperformance is a key factor in whether a site is running well,the performance and efficiency of the site affect the company's operating costs and long-term development, the production of high-quality and efficient code is our every developer must have the quality,is also our good professional accomplishment. second, the factors affecting the performanceA,Business needs1.Demand Rationality2.integration of requirements and systems3.whether the commercial benefits brought by demand are proportional to the cost of demand development4.the risks posed by demandB,WebServer1.Concurrency processing power2.capacity for high loads3.capacity for load balancing4.the ability to handle dynamic content and static content5. WebServer DeploymentC,DataBaseServer1.Concurrent Access2.deployment of the database server3.of the databaseShemawhether the schema and the table design are reasonable4.Data RetrievalD,Operating SystemE,Client RequestF,program/languageIII. Indicators for analyzing performance1.run time of the programMicrotime () 2.memory consumed by the program's OperationMemory_get_usage () 3.Parallel processing within a unit of time4.DiskIothe processingFour, the goal of optimizing performancefast, concurrent, low resource consumption (memory, diskIo,Cpuload)Five, the principle of optimizing performance1.Server Provisioning Optimization2.rationalization of server deployment3.commercial demand is reasonable and proportional to the commercial value of output4.architecture is available, maintainable, extensible5.The correctness, simplicity and rationality of the logic of the program. 6.constant Analysis of the bottleneck of performance7.constant refactoring of existing code8.Priority of Optimization:Program->database->web sersver->os->clientCode Optimization:(1) connection character use,Replace. Echo ' string1 ', $a, ' string2 ', $b;(2The maximum value is taken before the loop, not the value in the loop$max = count ($array); for ($i =0; $i < $max; $i + +) {echo $i; }(3) usingStaticstatic methods are faster than normal methods4Times,Staticrepresents a property that is initialized only onceDatainterface::getuserids ($UID);(4)in thePhpthe execution rate is from fast to slow in:Echo (), print (), Print_r (),Echois a PHP statement, print and Print_r are functions, the statement does not return a value, the function can have a return value (even if it is not used)(5) usingunsetreleases the given variable(6)Includesand theRequiresinclude file use full path(7) usingSTRNCASECMP, STRPBRKand theStriposReplaceRegex(8) usingSwitchReplaceIf ElseStatement(9) suppress the error character@Very low performance,Error function(10remember to close unnecessary database connections at any time(11)$row [' ID ']than$row [ID]Fast Performance7Times(12Adding a global variable is slower than adding a local variable2Times(13use single quotes instead of double quotation marks to refer to characters(14) usingHtmlthanPhpScript Fast2-20Times(15) usingPhpCaching accelerates performance25%-100%(16)$++than+ + $iSlow(17) do not overdo itOop, moderate and stop(18) try to usePhpbuilt-in functions·variables1,Small variable length,Note that variable size is the most efficient means of saving memory, and for data from user forms, databases, and file caches, you need to control the size of variables. becauseCputhe data to be processed comes from memory, and the longer the name is, the more time it takes to query .2,Unset ()It is a good habit to unregister unwanted variables, and to log off some unwanted variables immediately can increase memory usage. 3,try not to copy variables, or you will bring1times the memory consumption, even if the copy variable should be immediately unregistered the original variable. 4,Variable Type,Initialize variables note the variable type, and a variable is preferable to have only one type state during execution. For an array variable, initialize the declaration as follows:$a = Array (); 5,Temp Variable,is the temporary storage that handles the business logic, all of which require memory consumption. If the temporary variable is used, log off immediately, especially in the execution of some process code, for some functions, if the business is very complex, you also need to unregister the temporary variable immediately6,Static Variables,for some variables that need to be generated by complex business, if they are produced and used more than once during the execution of a program, consider using static variables to reduce programCpuNumber of executions7,Performance of variables: local variables>Global Variables>Class Properties>A variable that is not defined. ·Loops1,Minimize the number of cycles. 2,try to reduce the level of the circular flight, not more than three layers. 3,avoid having too much business logic within the loop. 4,do not loop include files5,do not loop through database operations. 6,Priority UseForeachit thanFor/whileHigh Efficiency7Don't putCount/strlen/sizeofput inForin the conditional statement of the LoopFor ($i =0, $count =count ($array); $i < $count; $i + +) {}Do not usefor ($i =0; $i <count ($array); $i + +) {};8,for ($i = $total; $i >0; $i–){}Better performance thanfor ($i =0; $i < $total; $–) {}9,Keep the business logic clear within the loop·function1,function is clear, a function is only one thing, do not mix too much business logic2,function code body do not exceed20line, instead, consider splitting. 3,Priority UsePhpbuilt-in functions, parameter acquisition of built-in functions,Zend_parse_parametersmethod, for arrays, strings, and other parameters,ZendThe implementation is a shallow copy, so this efficiency is very high. It can be said that forPhpbuilt-in functions, their efficiency and correspondingCfunctions are almost identical, with only one more forwarding call. 4,constants and functions are capable of doing one thing at the same time, using constants first. ·Phpversion () < php_version·Get_class () < __class__·Is_null () < null ===6,$_server[request_time]ReplaceTime (); 7,string SubstitutionSTRTR ()->str_replace ()->preg_replace ()->epreg (); 8,PlayTrimmaximum efficiency, replacementSubstr. $filepath =trim ($filename,'/').'/'; 9,Isset/emptywhile the functions of the two functions differ, it is recommended to use theEmpty () 10,Isfile/file_existthe functions of the two functions vary,File_existIt is possible to determine whether a file exists or not, and it is recommended to use it in the same situationIs_file11,Phppseudo-Functions inIsset Empty unset evalas can be seen from the above, the pseudo-function is executed by direct translation into instruction, and the overhead of a function call is less than the normal function, so performance is better. Mt_randAverage Speed ratiolibcprovided byRAND ()four times times faster. ·file1,reduce the number of file inclusions, reduce diskIO2,use a full path, or a relative path that is easy to convert. Avoid theInclude_pathFind3,do not exceed the number of code lines in the file2000Line4,Require_once/include_onceless efficientRequire/include,need additional to see if the system has already called this file.because they are in aOpCodethe calls under the cache are very slow5, program execution fileRequie/require_once,Cache files withInclude/include_once. Includebetter efficiency thanRequire6, optimizeSplautomatic file loading mechanism, can beYii7, class library file loading, whether the class is instantiated or not, consider a singleton pattern with design patterns8, the concurrency of file read and writeObject Oriented1,controlling the number of instances created2,Precedence with constants, class constants3,Static variables, static properties, for precedence cases4,the structure of the class is reasonable5,Surface Interface Programming6,Package Change Point7,dependent on abstraction, not on detail8,use static members first9,The interface of the class is clear and stable, the functions of class are single, and the communication between class and class is reasonable10,benefits of using constantscompile-time resolution with no additional overheadThe hash table is smaller, so the internal lookup is fasterclass constants exist only in a specific "namespace", so the hash name is shorterCleaner code to make debugging easierstring1,use single quotes instead of double quotation marks to reference strings; avoid retrieving variables in stringsarithmetic1,withI+=1ReplaceI=i+1. MeetC + +habits, high efficiency.4,If/elsewith the_&&,A single Statement of judgment please select&&the form,&&efficiency is higher thanIf/else, as follows: if ($a = = 1) {$b = 2;}you can choose to($a = = 1) && $b = 2;Cache1,UsePhpAccelerator, bufferingOpcode2,example withMemcache/nosql3,Use the In- memory database,4,using File Caching5,buffering functionother1,less Use@symbols that seriously affect performance2,close a remote resource connection, such as a database, as appropriateFtp,Socketand so on, timely cleanup of these resourcesB,Database Optimization1,a reasonable business need2,DatabaseSchemaArchitecture Optimization3,Vertical and horizontal sub-Library sub-table4,index optimization, query optimization5,Third party Open source search tool(Sphinx) 6,the use of the master-slave database server. C,Weboptimization of the server (not yet organized,have the correspondingWebServer Optimization manual)D,Operating System Optimizations(not organized,have the correspondingOSOptimization Handbook) E,Front-End optimization1, ReasonableHtmlstructure2, ReasonableHtmlwith theCssat the same time, considerCssreasonable design, reducehttpRequest3, ReasonableHtmlwith theJava Scriptconsider whether the split is reasonable and reducehttpRequest4, optimizeJava Scriptcode that gives the user a good experience5, according tohttpprotocol to optimize high concurrent requests1. a function can be done with built-in functions, try to use it instead of writing it yourselfPhpfunction. 2. If a feature has high performance requirements, consider extending it. 3. Phpfunction calls are expensive, so do not encapsulate them too much. Some features, if you need to call a lot of the times themselves and only use1,2If the line code is implemented, it is recommended that you do not encapsulate the call. 4. do not indulge in a variety of design patterns, as described in the previous article, excessive encapsulation will bring performance degradation. The tradeoff between the two needs to be considered. Phphave their own characteristics, must not parody, excessive imitationJavathe mode. 5. functions should not be nested too deep, recursive use to be cautious. 6. The performance of pseudo-function is high, and the same function is given priority. Like withIssetReplaceArray_key_exists 7. The function return reference does not make much sense and does not make a practical difference, and it is recommended not to be considered. 8. class member methods are less efficient than normal functions, so there is no need to worry about performance loss. It is recommended to consider static methods, which are more readable and more secure. 9. in the case of special needs, parameter passing suggests using a pass-through instead of a reference. Of course, reference passing can be considered if the parameter is a large array and needs to be modified. |