Writing a summary of PHP code

Source: Internet
Author: User
Tags empty execution functions variables php file strlen switch case variable

1-writing modular Code

Good PHP code should be modular code. The object-oriented programming capabilities of PHP are particularly powerful tools that can decompose your application into functions or methods. You should try to separate the front-end Html/css/javascript code as much as possible from the server side of your application. You can also follow MVC (model-View-controller) patterns on any PHP framework.


2-code Coding specification

Good PHP code should have a complete set of code coding specifications. You can make your code more readable by naming variables and functions, using a unified approach to accessing the database and handling errors, and the same code indentation to achieve the programming specification.



3-Writing portable code

Good PHP code should be portable. You can use PHP's existing features, such as magic quotes and short tags. Try to understand your needs and then write code that allows code to be independent and portable by adapting to PHP features.



4-Writing security Code

Good PHP code should be safe. PHP5 delivers excellent performance and flexibility. But the security issue is entirely about developers. For a professional PHP developer, an in-depth understanding of critical vulnerabilities is critical, such as Cross-site scripting (XSS), cross-site request forgery (CSRF), code injection vulnerabilities, and character encoding vulnerabilities. By using PHP's special features and functions, such as: mysql_real_escape_string, you can write safe code.



5-code Comment

Code comments are an important part of your code. The code annotation lets you know what the variable or function does, which will be useful in future code maintenance.



6-Avoid short labels

Replace all the short labels with the full PHP tags.



7-use single quotes instead of double quotes

strings always use single quotes instead of double quotes to avoid the performance degradation caused by variables within the PHP search string. It is quicker to use single quotes instead of double quotes to contain strings. Because PHP searches for variables in a string enclosed in double quotes, single quotes do not



8-Escape string Output

It is a good practice to pass the ent_quotes argument to the Htmlspecialchars function to ensure that single quotes (') are also converted into HTML entities.



9-Separate string output with commas

A string separated by commas (,) is output using the Echo statement, rather than using a string concatenation operator (.) Performance is better.



10-Check the value of the output before

Check the value passed in before the output $_get[' query ']. You can use the Isset or empty function to check whether a variable is a null value.

11-Other
  • If you can define a class's method as static, try to define it as static, and it will rise nearly 4 times times faster.
  • $row [' ID '] is 7 times times the speed of $row[id].
  • echo is faster than print, and uses Echo's multiple arguments (to refer to a comma rather than a period) instead of a string connection, such as Echo $str 1, $str 2.
  • To determine the maximum number of loops before executing the FOR loop, do not compute the maximum value per loop, preferably by using foreach instead.
  • Unregister those unused variables, especially large arrays, to free up memory.
  • Try to avoid using __get,__set,__autoload.
  • Require_once () is costly.
  • Include files when you use absolute paths, because it avoids the speed with which PHP looks for files in Include_path, and it takes less time to parse the operating system path.
  • Using $_server[' Request_time ' is better than time () if you want to know when the script starts executing (that is, the server receives the client request).
  • function to accomplish the same function instead of a regular expression.
  • The Str_replace function is faster than the Preg_replace function, but the STRTR function is four times times more efficient than the Str_replace function.
  • If a string substitution function can accept an array or character as an argument, and the parameter length is not too long, consider writing an extra paragraph of substitution code so that each pass parameter is a character, rather than writing a single line of code to accept the array as a query and replacement parameter.
  • Using the Select Branch statement (the switch case) is better than using multiple if,else if statements.
  • Using the @ block error message is very inefficient and extremely inefficient.
  • Open the Apache mod_deflate module, you can improve the browsing speed of the Web page.
  • The database connection should be turned off when it is finished and not long.
  • Error messages are costly.
  • Increments the local variable in the method, the speed is the fastest. Almost as fast as calling a local variable in a function.
  • Incrementing a global variable is twice times slower than incrementing a local variable.
  • Incrementing an object property (such as: $this->prop++) is 3 times times slower than incrementing a local variable.
  • Incrementing an undefined local variable is 9 to 10 times times slower than incrementing a predefined local variable.
  • Defining only one local variable, not calling it in a function, also slows down the speed (which is equivalent to incrementing a local variable). PHP will probably check to see if there are any global variables.
  • The method call appears to be independent of the number of methods defined in the class, because I added 10 methods (both before and after the test method), but there was no change in performance.
  • A method in a derived class runs faster than the same method defined in the base class.
  • Calls an empty function with one parameter, which takes as much time as 7 to 8 increments of local variables. A similar method invocation takes approximately 15 times of local variable increments.
  • Apache parses a PHP script 2 to 10 times times slower than parsing a static HTML page. Use static HTML pages as much as possible and use less scripting.
  • Unless the script can be cached, it will be recompiled every time it is invoked. The introduction of a set of PHP caching mechanisms typically increases performance from 25% to 100% to exempt compilation overhead.
  • Try to do caching, you can use memcached. Memcached is a high-performance memory object caching system that can be used to speed up dynamic Web applications and reduce database load. It is useful to cache the operation Code (OP code) so that the script does not have to recompile for each request.
  • When you manipulate strings and need to verify that their lengths meet certain requirements, you will of course use the strlen () function. This function executes fairly quickly because it does not do any calculations and returns only the known string lengths stored in the Zval structure (c's built-in data structure for storing PHP variables). However, since strlen () is a function, it will be somewhat slower, because function calls go through a number of steps, such as lowercase letters, PHP is case-insensitive, and hash lookups follow the functions that are called. In some cases, you can use the isset () technique to speed up the execution of your code.
    		(Examples below)  
  • 		(compare with the following techniques)  if (!isset ($foo [5])) {echo ' foo is too Short ';}    

    Calling Isset () happens to be faster than strlen (), because unlike the latter, Isset () as a language structure means that its execution does not require function lookup and lowercase. That is, you're actually not spending too much on the top-level code that verifies the length of the string.

  • $i + + $i slower than + + when the execution variable $i is incremented or decremented. This difference is specific to PHP and does not apply to other languages, so please do not modify your C or Java code and expect them to quickly become useless. + + $i faster because it requires only 3 instructions (opcodes), $i + + requires 4 instructions. A post increment actually produces a temporary variable, which is then incremented. And the predecessor increment increases directly on the original value. This is one of the most optimized processes, as Zend's PHP optimizer has done. Keeping this optimization in mind is a good idea, because not all command optimizer will do the same optimization, and there are a large number of Internet service providers (ISPs) and servers that do not have assembly instruction optimizer.
  • It's not something. object-oriented (OOP), object-oriented often expensive, each method and object invocation consumes a lot of memory.
  • Arrays are also useful not to implement all the data structures with classes.
  • Don't subdivide the method too much and think carefully about what code you really intend to reuse.
  • When you need it, you can always break the code into methods.
  • Try to use a lot of PHP built-in functions.
  • If there are a lot of time-consuming functions in your code, you might consider implementing them in C-extension mode.
  • Evaluate your code for the test (profile). The inspector will tell you which parts of the code are consuming much of the time. The Xdebug debugger includes a test procedure that can be used to show code bottlenecks in general.
  • Mod_zip can be used as an Apache module to instantly compress your data and reduce data transfer by up to 80%.
  • In the case of using file_get_contents instead of file, fopen, feof, fgets, and so on, use file_get_contents as much as possible, because of his high efficiency! But pay attention to file_get_contents in opening a URL file when the PHP version problem;
  • As little as possible to file operations, although the PHP file operation efficiency is not low;
  • Optimize the Select SQL statement and, if possible, minimize the INSERT and update operations (on update, I was a bad batch);
  • Use PHP's internal functions as much as possible (but I've wasted the time and experience of writing a custom function in order to find a function that doesn't exist in PHP). );
  • Do not declare variables inside the loop, especially large variables: objects (this seems to be not just a matter of note in PHP)? );
  • Multidimensional arrays do not loop nesting assignments as much as possible;
  • Do not use regular expressions when you can use PHP internal string manipulation functions;
  • foreach is more efficient and uses foreach instead of while and for loops as much as possible;
  • "Replace i=i+1 with I+=1." In line with C + + habits, efficiency is also high ";
  • For global variables, it should be unset () out;


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.