PHP uses static variables for caching (TIPS )?? I recently made an import function for the customer, which has a feature requirement. the customer has a media field. after the import, the imported media should be based on the imported media, check that some media data is updated to this customer's field .?? After I finish the test, the import function will be ready and delivered. in a short time, the customer will reflect the speed of using static variables for caching in PHP (tips)
?? I recently made an import function for the customer, which has a feature requirement. the customer has a media field. after the import, the imported media should be based on the imported media, check that some media data is updated to the customer's field.
?? After I finish the test, the import function is ready for delivery. in a short time, the customer will report that the import function is slow. when I check the cause, I find that it is related to some media data, although the SQL statement execution time is short, the time is extended because the imported data volume is large and every execution is required.
?? After analyzing the cause, we want to solve the problem. The developer can see it at a glance, that is, 'cache'. what technology is used to analyze the problem and find out:
?? 1. there are a huge number of import customers, but many of the customer's media is repeated, and many SQL statements are executed repeatedly.
??? 2. because the media information is updated, it can be determined that the data obtained from the same media in this access is the same, so the cache validity time is only the connection time.
?? 3. the cache speed should be as fast as possible. As we all know, the cache speed varies depending on the local memory> memcache> disk cache.
??? These three features can be cached using static variables. The basic code format is as follows:
???
Function updateFirstEndFromBatchtasks (...) {static $ cache = array (); $ val = $ cache [$ key]; if (is_null ($ val) {$ val = ..... // get the value of $ val $ cache [$ key] = $ val ;}}
?
? The following describes the advantages and disadvantages of static variables for caching:
?? Advantages:
?? Fast, efficient, and easy to implement. Because it is a PHP internal variable, it is the most efficient in all caches.
?? Disadvantages:
?? Poor flexibility. it is only valid in this connection and has a small execution area. it is only valid in the same function and cannot operate across functions (you can use global variables instead ).
?? Static variables are very useful for caching and consume a small amount of resources. for those that want to query the database and may be executed multiple times in a connection, you can add them. Although the effect may be limited.