This is a translation of the first 10 tips of the
article on optimizing PHP code. On Habré there is a translation of an older version of the article -
40 tips for optimizing your PHP codeI tried not only to supplement the already existing translation with additional tips, but to clarify why this would be faster, and added my thoughts about the meaning of such optimization, based on their experience in developing and working in different teams.
I am writing in parts, otherwise I will get a lot of material at once.
')
This is my first article on Habré, I hope it turned out to be interesting.
Notice:In this article, I often disagree with the tips from the original article. My inserts are in italics. And I try to make arguments for why I agree or disagree with optimization tips.
I am not responsible for the accuracy of the tests, I myself did not conduct tests. If only because for most of the advice the difference is very small for most possible cases, and other factors play a key role - readability, scalability, flexibility. And financial justification.
I do not pretend to be an expert, and I do not consider my comments on the tips as direct instructions for action. And even less I urge you to use the advice of the original article.
The main purpose of why I decided to sit down and write this article is an attempt to resolve disputes about the need for optimization, “saving on matches”.
What I consider for myself (because I read somewhere, based on experience, etc.) and I want to give it in the form of a list:
1. You should not do the optimization ahead of time, at the development stage
2. Do not save on matches
3. Pay attention first and foremost to the most bottlenecks, and where optimization will be most effective
4. Your code must be readable, scalable, flexible. (but depending on the task, the requirements may be different).
Notes:- The author uses the text "[Citation]" for the title of all links, however, some of the links lead to tests proving statements about performance, for example, one or another construction, and often references to useful resources. I will call the references leading to the tests "[test]", and leading to useful resources "[useful information]", and the articles respectively "[article]".
- My additions will be italicized.
Important! I do not urge to use optimization tips from the original article. On the contrary, I try to consider the meaning of these tips in italicized lines, to refute the tips, or to consider cases when their use makes sense. Before reading, I want to once again remind the old truth that premature optimization only worsens the development process, and your code. And do not save on pennies.
All that I added to the original is my experience, my knowledge, which I share.
To readers: This article is addressed first and foremost not to the web development gurus, but to those who are just gaining experience. But I hope that it will be interesting and professional.
Go :)
1.
echo is faster than
print .
[test]Yes, and write one letter less. But rather this advice for common development. Most programmers use echo . The performance boost is minimal. And in serious echo projects, a rarely occurring construct. Because the conclusion is usually collected first, and then discarded.2. Strings enclosed in single quotes' rather than double doubles faster because PHP searches for variables inside strings enclosed in double quotes. Enclose strings in single quotes when there are no variables in it.
[Article]Visually, strings in single quotes are read and perceived better. But when it's just strings, not variable strings, concatenated by concatenation. In this case, the performance gains are provided just by variables inserted into strings framed with double quotes. In addition, the fascination with concatenation looks unreadable.3. Use
sprintf instead of variables enclosed in double quotes. It is about 10 times faster.
[test]This is most likely due to the fact that if you use sprintf, then PHP refers to the C function sprintf. Which by itself is faster than if PHP itself will produce parsing the line itself, written in C. However, I don’t think that such code will be easy enough to read. Perhaps this makes sense on very high-load projects, where a lot of work is done with strings, and using sprintf can give a tangible gain in performance. But I do not imagine such projects. Usually everything falls in other places.4. Pass several parameters to echo instead of string concatenation.
[article]It is logical that it works faster due to the fact that there is no concatenation that takes time. And the parameters one by one are thrown into the output stream. As for readability, I personally find it more convenient to read multiple parameters than concatenation, but perhaps not for everyone:echo $a, 'text', $b, 'more text'; //
echo $a . 'text' . $b . 'text'; //
According to the eyes , according to the results of the phpbench.com test, the concatenation of constant strings for echo is faster than if you pass them with multiple parameters5. Do not use the calculation of the number of elements of the array, the length of the string, etc., to determine the last iteration of the loop in the loop itself. Set the maximum value for the for loop before it. For example:
for ($ x = 0; $ x <count ($ array); $ x) , calls
count () at each iteration, use
$ max = count ($ array); before the cycle. link [test]
This is a long-known fact. The test shows the difference in performance 10 times. If there is a fairly large array of data, or similar calculations occur frequently, it is worth considering. Readability is not affected in any way.6. Deflate or reset your variables to free up memory, especially if they are large arrays.
[useful information]This also applies to deleting the database query results from the buffer, for example. But deleting all unused variables greatly reduces the readability of the code. Using variables wherever possible is also not a sign of a good programming style://
$time = time();
$login = $_SESSION['login'];
$hash = md5($login . $time);
//
$hash = md5( $_SESSION['login'] . time() );
in case this construction is used once. So the eye perceives the code better. Because it is in one line. But you should not get involved here, because it can again lead to unreadable. But this is a purchase.
Optimization to free up memory from resources (variables, database query results, etc.) should be done already on a finished application under load, and only if it is really large resources. Then you can evaluate the benefits of such optimization.7. Avoid magic methods such as
__get, __set, __autoload [useful information]... And also __call, __toString ... Not justified. As for example overload greatly simplifies development, and reduces the amount of code. About __autoload is a controversial point. In my experience, it is convenient. But at the same time, if a new person comes to the project, it would be more obvious for him to have direct inclusions than to use __autoload (), and accordingly it would take less time to join the project.8. Whenever possible, use
require () instead of
require_once () .
[article]Very unjustified savings. With require instead of require_once it is much more likely to load a file that has already been uploaded, which obviously does not reduce the execution time of the code. And it makes you worry too much about whether this file is not already a friend, which is especially important in team work, and greatly slows down the development9. Use full paths in
include (_once) and
require (_once) , thereby reducing the time to allow OS paths.
[article]This is reasonable for another reason. When a script that is not in the document_root root, you need to load another script that is either higher or much lower. This allows you to not worry about the location of the scripts in the project relative to each other when they are connected. But for paths, it is better to define constants using $ _SERVER ['DOCUMENT_ROOT'], or getcwd (). Also sometimes there is a failure of the paths in the settings of php.ini, that PHP is simply not looking for scripts in document_root, and this technique allows you to protect yourself from this. And the use of different constants for different folders allows you to increase the readability of the code. For example:
TEMPLATES_DIR
CORE_DIR
MODULES_DIR
10.
require () and
include () are identical in all respects with the exception that
require stops the execution of the script, in the case when the included file is not found. The difference in speed is minimal.
include () if the file is not found, issues a warning, and require terminates the application. In most cases, especially considering that on the working server, error output is disabled, not including any of the files is critical, and it is better to stop the application than to catch a bunch of warning messages from other components that required different resources and functionality of the file (class, constants, functions, etc.)
Files connected via require include files at the beginning of the execution stage, and include during interpretation. And if include is inside an if block, and the condition is not met, the file will not be included.The remaining 40+ tips will be in the near future.