Home Backend Development PHP Tutorial Use static to avoid 'repeated reading'_PHP tutorial

Use static to avoid 'repeated reading'_PHP tutorial

Jul 21, 2016 pm 02:55 PM
static web use exist complex object operate data of Program development avoid use For

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:
以下为引用的内容:
//要改写的函数也请加上$is_static=1变量,用来控制是否开启 static。
function staticFunc ($var1,$var2,$var3,$is_static=1)
{
if ( $is_static == 1 )//默认需要缓存函数结果
{
static $result_array;//该数组用来保存函数的结果,支持不同参数的结果缓存
$vars_string = serialize( func_get_args() );

if ( empty( $result_array ) )//第一次运行需要初始化
{
$result_array = array();
}

if ( array_key_exists( $vars_string, $result_array ) )//参数已经存在
{
return $result_array[$vars_string];//返回静态变量中已经保存的结果
}else//参数不存在
{
$result_array[$vars_string] = '';//后面会把结果补充进来
}
}else//不利用static 缓冲结果
{
if ( empty( $result_array ) )
{
$result_array = array();
}
}

$result_array[$vars_string] = rand();//获取结果,请把获取的代码放在此处即可
return $result_array[$vars_string];
}

echo staticFunc(1,2,3);
echo "
";
echo staticFunc(2,2,2);
echo "
";
echo staticFunc(1,2,3);
echo "
";
echo staticFunc(2,2,2);
echo "
";
echo staticFunc(3,3,3);
echo "
";
echo staticFunc(3,3,3,0);
echo "
";
?>
"; echo staticFunc(2,2,2); echo "
"; 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/

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/364345.htmlTechArticleIn the development of more complex web programs, due to the use of object-oriented data operation methods, or the business logic is too complex , developers often read repeatedly unconsciously during the development process...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Apr 03, 2024 pm 12:04 PM

0.What does this article do? We propose DepthFM: a versatile and fast state-of-the-art generative monocular depth estimation model. In addition to traditional depth estimation tasks, DepthFM also demonstrates state-of-the-art capabilities in downstream tasks such as depth inpainting. DepthFM is efficient and can synthesize depth maps within a few inference steps. Let’s read about this work together ~ 1. Paper information title: DepthFM: FastMonocularDepthEstimationwithFlowMatching Author: MingGui, JohannesS.Fischer, UlrichPrestel, PingchuanMa, Dmytr

Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Apr 01, 2024 pm 07:46 PM

The performance of JAX, promoted by Google, has surpassed that of Pytorch and TensorFlow in recent benchmark tests, ranking first in 7 indicators. And the test was not done on the TPU with the best JAX performance. Although among developers, Pytorch is still more popular than Tensorflow. But in the future, perhaps more large models will be trained and run based on the JAX platform. Models Recently, the Keras team benchmarked three backends (TensorFlow, JAX, PyTorch) with the native PyTorch implementation and Keras2 with TensorFlow. First, they select a set of mainstream

The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks Apr 29, 2024 pm 06:55 PM

I cry to death. The world is madly building big models. The data on the Internet is not enough. It is not enough at all. The training model looks like "The Hunger Games", and AI researchers around the world are worrying about how to feed these data voracious eaters. This problem is particularly prominent in multi-modal tasks. At a time when nothing could be done, a start-up team from the Department of Renmin University of China used its own new model to become the first in China to make "model-generated data feed itself" a reality. Moreover, it is a two-pronged approach on the understanding side and the generation side. Both sides can generate high-quality, multi-modal new data and provide data feedback to the model itself. What is a model? Awaker 1.0, a large multi-modal model that just appeared on the Zhongguancun Forum. Who is the team? Sophon engine. Founded by Gao Yizhao, a doctoral student at Renmin University’s Hillhouse School of Artificial Intelligence.

Slow Cellular Data Internet Speeds on iPhone: Fixes Slow Cellular Data Internet Speeds on iPhone: Fixes May 03, 2024 pm 09:01 PM

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. May 07, 2024 pm 05:00 PM

Recently, the military circle has been overwhelmed by the news: US military fighter jets can now complete fully automatic air combat using AI. Yes, just recently, the US military’s AI fighter jet was made public for the first time and the mystery was unveiled. The full name of this fighter is the Variable Stability Simulator Test Aircraft (VISTA). It was personally flown by the Secretary of the US Air Force to simulate a one-on-one air battle. On May 2, U.S. Air Force Secretary Frank Kendall took off in an X-62AVISTA at Edwards Air Force Base. Note that during the one-hour flight, all flight actions were completed autonomously by AI! Kendall said - "For the past few decades, we have been thinking about the unlimited potential of autonomous air-to-air combat, but it has always seemed out of reach." However now,

Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! May 06, 2024 pm 04:13 PM

The latest video of Tesla's robot Optimus is released, and it can already work in the factory. At normal speed, it sorts batteries (Tesla's 4680 batteries) like this: The official also released what it looks like at 20x speed - on a small "workstation", picking and picking and picking: This time it is released One of the highlights of the video is that Optimus completes this work in the factory, completely autonomously, without human intervention throughout the process. And from the perspective of Optimus, it can also pick up and place the crooked battery, focusing on automatic error correction: Regarding Optimus's hand, NVIDIA scientist Jim Fan gave a high evaluation: Optimus's hand is the world's five-fingered robot. One of the most dexterous. Its hands are not only tactile

See all articles