使用static来避免“重复读”
在较复杂的web程序开发中,由于采用面向对象的数据操作方式,或者业务逻辑太过复杂,开发人员在开发过程中,经常会无意识的重复读取数据。
比如:
$result1 = tableobjectPeer::getResult($var1,$var2,$var3);
开发人员在需要的该table数据的时候,经常直接调用 tableobjectPeer::getResult方法。
又或者程序在进行forward的时候,也会导致重复调用 tableobjectPeer::getResult 方法,导致“重复读”。
要避免类似的“重复读”,最主要的办法是,开发人员在代码开发的时候,就要有“避免重复读”的意识。
其实只要在:
$result1 = tableobjectPeer::getResult($var1,$var2,$var3);
之后,需要的地方进行
$result2 = $result1;
$result3 = $result1;
即可。这样子就可以避免掉大量的“重复读”了。
但是如果开放人员一开始没有这样做,那要进行这方面的重构可能是很大的工作量。
另外,由于框架中的forward()也容易造成“重复读”。如果“重复读”是forward()造成的,那该方法就不可行了(这点也许和不同的开发语言,不同的开发框架有关,在php的symfony框架中是如此)。
因此,在采用上面的方法进行优化的同时,对于一些较复杂的情况,决定采用另一种方式:使用static,设置变量为静态变量,来避免重复读取数据。
以下为引用的内容: //要改写的函数也请加上$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 " "; ?> |
运行上述代码,产生的结果类似:
16667
8888
16667
8888
2193
1014
可以看出,第1行和第3行的结果一致,第2行和第4行的结果一致,说明只要函数的参数相同,函数结果就进行了有效的“cache”。
从第4行和第5行,可以看出,通过设置$is_static变量能有效控制是否开启“cache”。
补充:上述使用static方法,可以有效的避免在一个线程内,重复读取数据,但是该cache只存在一个线程内,不同线程是相互独立的。虽然只是线程内的函数结果“cache”,但是其原理和其他方式的cache是类似的,就是要针对不同的参数(不同的情况)构造出cache的key。
转自:http://www.cnblogs.com/rethink/

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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

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

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

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

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.

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

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

New SOTA for multimodal document understanding capabilities! Alibaba's mPLUG team released the latest open source work mPLUG-DocOwl1.5, which proposed a series of solutions to address the four major challenges of high-resolution image text recognition, general document structure understanding, instruction following, and introduction of external knowledge. Without further ado, let’s look at the effects first. One-click recognition and conversion of charts with complex structures into Markdown format: Charts of different styles are available: More detailed text recognition and positioning can also be easily handled: Detailed explanations of document understanding can also be given: You know, "Document Understanding" is currently An important scenario for the implementation of large language models. There are many products on the market to assist document reading. Some of them mainly use OCR systems for text recognition and cooperate with LLM for text processing.
