Log in / create account | Login with OpenID
DocForge
Programmer's Wiki

PHP/Performance

From DocForge

< PHP

PHP, like every programming language implementation, has certain performance characteristics. Being aware of them and coding consistently can help improve web application performance. Some practices provide relatively small gains, but can make a difference when used regularly. Many teams like to include these practices in their coding standards.

Contents

[edit] Code Organization

require_once and include_once can be relatively expensive operations. Only include the files which are required for a given set of code, as opposed to always including all source code files within every other file of an entire project.

Relative paths also make the include and require statements more expensive by forcing the PHP runtime to resolve the path. Use absolute paths whenever possible.

[edit] Strings

PHP has four types of strings declared within code. Strings within double quotes and heredoc have their variables evaluated (or "expanded") and many escape sequences interpreted. Strings within single quotes and nowdoc do not cause any variable evaluation and only support escaping of single quotes and backslashes. Therefore double quotes and heredoc require more evaluation and processing. When no variable evaluation and no special characters are required, using single quotes will provide better performance.

Inline string concatenation is supported in PHP with the period character. Using this simple inline concatenation can require multiple memory allocations. Using the implode function requires only one memory allocation and can therefore be more efficient.

Regular expressions are relatively expensive to process. When possible, use simple string functions instead, such as str_replace and strstr.

[edit] Memory Consumption

Use simple tools, like PHP's built-in functions memory_get_usage and memory_get_peak_usage, to gather memory consumption characteristics. Using these within an application can trap segments of code which are problematic. Comparing memory usage before and after a section of code, then logging these values, will provide accurate metrics.

Implicit garbage collection occurs (basically) when a variable falls out of scope, such as at the end of a function or script. Explicitly unsetting a variable can free its memory before PHP does automatically. This is especially useful in long running scripts, such as some cron jobs, which can explicitly free some memory used early in a script before waiting for the task to complete.

When using the Smarty templating engine, expect a memory usage spike when a template is first compiled. Following it's compilation upon first use or after an edit, this spike won't occur.

[edit] See Also

Do you have information or insights to contribute to this article? Please feel free to edit this page. Ask questions or contribute to the discussion on this article's talk page.