Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the problems that need to be paid attention to in PHP coding?

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Usually in PHP coding need to pay attention to what problems, I believe that many inexperienced people are helpless about this, this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

Write a good hand of code, this is the need for you to accumulate in the usual development, usually if you have noticed the following code coding, then congratulations, you have laid some foundation in this aspect of skill improvement, write a good hand of code, to put it bluntly, you pay attention to the performance of this piece of the problem, code optimization is also part of the performance optimization. Next, let's look at the code you usually need to pay attention to. I hope you get into good habits too!

1. Use single quotes instead of double quotes to enclose strings, which is faster. Because PHP searches for variables in double-quoted strings, single-quoted strings don't, note that only echo can do this, which is a "function" that can take multiple strings as arguments.

If you can define a class method as static, try to define it as static, and it will be nearly 4 times faster.

$row[id] is seven times faster than $row[id].

Echo is faster than print and uses multiple parameters of echo instead of string concatenation, such as echo $str1,$str2.

5. Determine the maximum number of loops before executing the for loop. Don't calculate the maximum value once every loop. It's best to use foreach instead.

Unregister unused variables, especially large arrays, to free up memory.

Try to avoid__get,__set,__autoload.

require_once() is expensive.

Use absolute paths when you include files, because it avoids the speed at which PHP finds files in include_path and takes less time to parse operating system paths.

If you want to know when the script starts executing, use $_SERVER ['REQUEST_TIME'] rather than time()

Functions replace regular expressions to accomplish the same function.

The str_replace function is faster than the preg_replace function, but the strtr function is four times as efficient.

If a string substitution function accepts arrays or characters as arguments, and the arguments are not too long, consider writing an additional substitution code so that each argument is passed one character at a time, rather than just writing one line of code to accept arrays as arguments for queries and substitutions.

14. Use a switch case rather than multiple if, else if statements.

The practice of masking error messages with @ is very inefficient, extremely inefficient.

Open mod_deflate module of apache to improve browsing speed of web pages.

17, database connection should be closed when used, do not use long connection.

Error messages are expensive.

Incrementing local variables in methods is the fastest. Almost as fast as calling local variables in a function.

Incrementing a global variable is twice as slow as incrementing a local variable.

Incrementing an object attribute (e.g.,$this->prop++) is three times slower than incrementing a local variable.

Incrementing an undefined local variable is 9 to 10 times slower than incrementing a predefined local variable.

Defining a local variable without calling it in a function also slows things down (by the same amount as incrementing a local variable). PHP probably checks to see if global variables exist.

Method invocations seem 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.

Methods in derived classes run faster than the same methods defined in the base class.

Calling an empty function with one argument takes the equivalent of 7 to 8 local variable increments. A similar method call takes approximately 15 local variable increments.

Apache parses a PHP script 2 to 10 times slower than parsing a static HTML page. Use static HTML pages more often than scripts.

Unless the script can be cached, it is recompiled once every time it is invoked. Introducing a PHP caching mechanism can typically improve performance by 25 to 100 percent to eliminate compilation overhead.

29, try to do cache, can use memcached. Memcached is a high-performance in-memory object caching system that can be used to speed up dynamic Web applications and reduce database load. Caching of op code is useful so scripts don't have to be recompiled for each request.

When manipulating strings and checking whether their length meets certain requirements, you would naturally use the strlen() function. This function executes fairly quickly because it doesn't do any calculations and just returns the known string length stored in the zval structure (C's built-in data structure for storing PHP variables).

However, since strlen() is a function, it is somewhat slow, because the function call goes through many steps, such as lowercase letters, hash lookup, and execution along with the called function. In some cases, you can use the isset() technique to speed up the execution of your code.

(Example below) if (strlen($foo) < 5) { echo "Foo is too short"$$ } isset($foo{5}) { echo "Foo is too short"$$ } Calls to isset() happen to be faster than strlen() because, unlike strlen(), isset() is a language construct meaning that its execution does not require function lookups and lowercase letters. That is, you don't actually spend a lot of overhead checking string length in top-level code.

When incrementing or decrementing the variable $i,$i++ is slower than ++$i. This difference is PHP specific and doesn't apply to other languages, so don't modify your C or Java code and expect it to be faster immediately. ++$i is faster because it requires only 3 opcodes, whereas $i++ requires 4. Post-incrementing actually produces a temporary variable that is then incremented. The pre-increment increases directly on the original value. This is one of the optimizations, as Zend's PHP optimizer does. It's a good idea to keep this optimization in mind because not all command optimizers do the same optimization, and there are a lot of ISPs and servers that don't have command optimizers.

It is not necessarily object-oriented (OOP), object-oriented is often expensive, and each method and object call consumes a lot of memory.

It is not necessary to implement all data structures with classes, arrays are also useful.

Don't break down methods too much, think carefully about what code you really intend to reuse.

You can always break down code into methods when you need them.

Try to use as many PHP built-in functions as possible.

If there are a lot of time-consuming functions in your code, consider implementing them as C extensions.

38. Evaluate your profile. The verifier will tell you which parts of the code are consuming how much time. The Xdebug debugger includes a validator that evaluates the validator to reveal bottlenecks in the code as a whole.

mod_zip can be used as an Apache module to compress your data instantly and reduce data transfer by 80%.

When file_get_contents can be used instead of file, fopen, feof, fgets, etc., try to use file_get_contents because it is much more efficient! But be aware of file_get_contents PHP version issues when opening a URL file;

41, as little as possible for file operations, although PHP file operation efficiency is not low;

42. Optimize the Select SQL statement and perform Insert and Update operations as little as possible (on update, I was criticized);

43. Use PHP internal functions as much as possible (but I wasted time writing a custom function in order to find a function that does not exist in PHP, experience problem ah!);

44. Do not declare variables inside the loop, especially large variables: objects (this seems to be more than just a problem to pay attention to in PHP?);

45. Multidimensional arrays should try not to loop nested assignments;

46. Do not use regular expressions when you can manipulate functions with PHP internal strings;

Foreach is more efficient, try to replace while and for loops with foreach;

48. Use single quotes instead of double quotes to quote strings;

49."Replace i=i+1 with i+=1. C/C++ habits, efficiency is also high "

50. For global variables, unset() should be used up;

After reading the above content, do you have any methods to master the problems that need to be paid attention to when coding PHP? If you still want to learn more skills or want to know more related content, welcome to pay attention to the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 295

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report