40 способов оптимизировать Ваш PHP-код
Ноябрь 4, 2007
Перевод оригинальной статьи «40 Tips for optimizing your php Code». Рассматриваются пункты, которые помогут Вашим программам работать быстрее и стабильнее без использования сторонних приложений (бинарников системы).
Если Вы научитесь (и не будете лениться) использовать эти простые правила в процессе программирования на языке PHP, то миф о прожорливости PHP для себя уж точно развеяте.
Удачного кодинга
- Если метод класса может быть объявлен как статический — объявляйте его так. Улучшение быстродействия — согласно пункту 4
- Оператор вывода echo быстрее, чем print (и print_r, соответственно, т.к. отсутсвуют проверки на тип выводимых данных // Jeurey)
- Используйте вывод типа echo ($str1,$str2,$str3); вместо echo ($str1.$str2.$str3);
- Устанавливайте максимальное значение циклов вне области их действия
- Используйте unset для освобождения памяти. Особенно это касается больших массивов (и строк, в частности)
- Лучше обходить стороной «магические» функции вроде __get, __set, __autoload
- Использование require_once () сопряжено с потерей быстродействия
- Используйте полные пути к скриптам, что позволит сэкономить время на опросе ОС на предмет местонахождения самого скрипта.
- ЕслиВам нужно замерить время исполнения скрипта — используйте $_SERVER[’REQUEST_TIME’]. Это предпочтительнее чем код с использованием time () и быстрее.
- Если есть возможность использовать функции strncasecmp, strpbrk и stripos вместо регулярных выражений — не упускайте ее!
- str_replace быстрее, чем preg_replace, однако strtr быстрее чем str_replace согласно пункту 4.
- Лучше использовать выбор состояний (switch... case... default), нежели многократно использовать if (st) {action;}
- Подавление ошибки через @ очень замедляет выполнение операции.
- Включите mod_deflate у Apache, если это возможно
- Закрывайте соединение с MySQL-сервером, если вы закончили работу с ним
- Используйте обращение к элементу массива вида $arr ['key']вместо $arr[key] — это в 7 раз быстрее
- Использование сообщений об ошибках дорого обходится для быстродействия.
- Не используйте вызов функции в цикле, если это возможно. Например — «for ($x=0; $x < count ($array); $x)» каждый раз производит подсчет размера массива.
- Инкрементация локальной переменной быстрее, чем глобальной в 2 раза.
- Инкрементация локальной переменной метода быстрее, чем переменной класса в 3 раза (например, $this->counter++).
- Инкрементация неустановленной переменной в 9-10 раз медленнее, чем установленной на ноль.
- Метод производного класса работает быстрее, чем метод базового класса
- Использование окружения строки в одинарных кавычках увеличивает скорость обработки вашего кода со стороны PHP, нежели использование двойнх кавычек.
Непереведенное
- If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
- Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
- Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
- A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.
- When echoing strings it's faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.
- A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
- Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.
- Cache as much as possible. Use memcached — memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request
- When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen () function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen () is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset () trick.Ex.
if (strlen ($foo) < 5) { echo «Foo is too short»; }
vs.
if (!isset ($foo{5})) { echo «Foo is too short»; }Calling isset () happens to be faster then strlen () because unlike strlen (), isset () is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length. - When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
- Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
- Do not implement every data structure as a class, arrays are useful, too
- Don't split methods too much, think, which code you will really re-use
- You can always split the code of a method later, when needed
- Make use of the countless predefined functions
- If you have very time consuming functions in your code, consider writing them as C extensions
- Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview
- mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%
- Excellent Article about optimizing php by John Lim
Январь 30, 2008 в 05:00
Hello!
Nice site
Bye
Апрель 8, 2008 в 02:15
Очень полезная информация, спасибо.
Я примерно половину знал из того, что написано.