Home >Backend Development >PHP Tutorial >Use static to avoid 'repeated reading'_PHP tutorial
In the development of more complex web programs, due to the object-oriented data operation method or the business logic is too complex, developers often unconsciously read data repeatedly during the development process.
For example:
$result1 = tableobjectPeer::getResult($var1,$var2,$var3);
When developers need the table data, they often call the tableobjectPeer::getResult method directly.
Or when the program is forwarding, it will also cause repeated calls to the tableobjectPeer::getResult method, resulting in "repeated reading".
To avoid similar "repeated reading", the most important way is for developers to have the awareness of "avoiding repeated reading" when developing code.
In fact, just do it where needed after:
$result1 = tableobjectPeer::getResult($var1,$var2,$var3);
$result2 = $result1;
$ result3 = $result1;
is enough. In this way, a large number of "repeated reads" can be avoided.
But if the developers didn't do this at the beginning, it may be a lot of work to refactor in this area.
In addition, due to the forward() in the framework, it is easy to cause "repeated reading". If "repeated reading" is caused by forward(), then this method is not feasible (this may be related to different development languages and different development frameworks, as is the case in PHP's symfony framework).
Therefore, while using the above method for optimization, for some more complex situations, we decided to use another method: Use static and set the variable to a static variable to avoid repeated reading of data. .
The following is the quoted content:
"; echo staticFunc(1,2,3); echo " "; echo staticFunc(2,2,2); echo "< ;br>"; echo staticFunc(3,3,3); echo " "; echo staticFunc(3,3,3,0); echo "< ;br>"; ?> |
Running the above code produces results similar to:
16667
8888
16667
8888
2193
1014
It can be seen that the results of lines 1 and 3 are consistent, and the results of lines 2 and 4 are consistent, indicating that as long as the parameters of the function are the same, the function results are effectively "cache".
From lines 4 and 5, it can be seen that setting the $is_static variable can effectively control whether to enable "cache".
Supplement: Using the static method above can effectively avoid reading data repeatedly in one thread, but the cache only exists in one thread, and different threads are independent of each other. Although it is just the "cache" of the function result within the thread, its principle is similar to other methods of cache, that is, the cache key must be constructed for different parameters (different situations).
Reprinted from: http://www.cnblogs.com/rethink/