PHP optimizations (was: [Typo3-dev] decrease memory usage)
Martin Kutschker
Martin.T.Kutschker at blackbox.net
Tue Sep 9 09:42:40 CEST 2003
Date: Mon, 08 Sep 2003 18:55:55 +0200
From: Kasper Skarhoj <kasper at typo3.com>
> From http://phplens.com/lens/php-book/optimizing-debugging-php.php
A very interesting read, ineed!
So using references for objects do help.
Also worth noting in regards to the original question:
# Unset() variables that are not used anymore to reduce memory usage.
This is mostly useful for resources and large arrays.
Some ideas for more optimization mentioned on the page:
# Use ob_start() at the beginning of your code. This gives you a 5-15%
boost in speed for free on Apache. You can also use gzip compression
for extra fast downloads (this requires spare CPU cycles).
# Optimize your loops first. Move loop invariants outside the loop.
# Use the array and string functions where possible. They are faster than writing equivalent code in PHP.
Note: this is of course true for the upcoming encoding functions. iconv/recode and mbstring should IMHO be favoured for self written PHP functions. There's no need to reinvent the wheel anyway.
# For searching for substrings, the fastest code is using strpos(), followed by preg_match() and lastly ereg(). Similarly, str_replace() is faster than preg_replace(), which is faster than ereg_replace().
# Use foreach() for iterating through arrays.
# Echo is slightly faster than print because echo does not return a value and (this is more important) there is no need to concatenate strings or variables with echo() pass them as multiple comma separated arguments:
echo $var1, $var2;
print $var1 . $var2;
# When concatenating multiple long strings together, consider storing the separate strings in an array and concatenate them using implode(). This can be faster than using the dot operator because the dot operator makes multiple memory allocations, while implode() allocates the string buffer only once. From my benchmarks and on my hardware configuration, the combined string has to be greater than 40K, and each sub-string at least 100 characters, for implode() to offer any performance advantage.
And of course - most important!
# Tune your database and index the fields that are commonly used in your SQL WHERE criteria.
# Use HTML caching if you have data that rarely changes. Even if the data changes every minute, caching can help provided the data is synchronized with the cache. Depending on your code complexity, it can improve your performance by a factor of 10.
Not mentioned here, but in such a large application like Typo3 it could make a difference: use single quotes instead of double quotes if you don't need variable interpolation.
Masi
More information about the TYPO3-dev
mailing list