Use static variables in PHP for caching (TIPS)
?? I recently for the customer to do an import function, there is a requirement, the customer has a media field, after the import to import the customer's media, to find out some of the media updates to this customer field.
?? When I finished, test import function No problem, then delivered, after a while, the customer reflects a bit slow, in check the reason, found and find out some of the media data about, although the SQL statement execution time is very short, but because the import data volume is very large, every time to execute, resulting in longer time.
?? After analyzing the reason, we want to solve the solution, the development of the people know, is ' cache ', that specific use of what technology, analysis of the problem, you can find:
?? 1. The import of the customer is huge, but many of the customer's media are duplicated, and many SQL statements are repeated.
??? 2. Due to the update of the media information, but it can be determined that the same media access to the same data, so the validity time of this cache is only this connection time.
?? 3. Cache the speed as fast as possible. It is well known that the speed of different caches is different, local memory >memcache> disk cache.
??? With these three features, you can use a static variable to implement caching. The basic form of the code is as follows:
???
function Updatefirstendfrombatchtasks (...) { static $cache =array (); $val =$ $cache [$key]; if (Is_null ($val)) { $val =.....//gets the value of $val $cache [$key]= $val; }}
?
? Let's talk about the static variables to implement the advantages and disadvantages of caching:
?? Advantages:
?? Fast speed, high efficiency, easy to achieve. Because it is a PHP internal variable, it is the most efficient execution in all caches.
?? Disadvantages:
?? The flexibility is poor, only valid in this connection, the execution area is small, only valid in the same function, cannot work across functions (can use global variable substitution).
?? Static variable cache is very useful, and the cost of a few resources, for the database to query, and in a single connection may be executed multiple times, it may be added. Although the effect may be limited.