PHP程序加速探索的代码优化方法_PHP
握了PEAR::BenchMark,现在你已经知道如何测试你的代码,知道如何判断你的代码是快是慢,是哪一部份比较慢。那么接下来我要说的就是如何消灭或优化那部份慢的代码。
这一点上我个人最主要的经验只有两点,一是消除错误的或低效的循环;二是优化数据库查询语句。其实还存在一些其它的优化细节,比如“str_replace比ereg_replace快”、“echo比print快”等等。这些我暂时都放在一边,稍后我会提到用缓存来对付过于频繁的IO。
下面我们将三个功能相同,但程序写法不同的函数的效率(消耗的时间)进行对比。
badloops.PHP
<?php
require_once('Benchmark/Iterate.php');
define('MAX_RUN',100);
$data = array(1, 2, 3, 4, 5);
doBenchmark('v1', $data);
doBenchmark('v2', $data);
doBenchmark('v3', $data);
function doBenchmark($functionName = null, $arr = null)
{
reset($arr);
$benchmark = new Benchmark_Iterate;
$benchmark->run(MAX_RUN, $functionName, $arr);
$result = $benchmark->get();
echo '<br>';
printf("%s ran %d times where average exec time %.5f ms",
$functionName,$result['iterations'],$result['mean'] * 1000);
}
function v1($myArray = null) {
// 效率很差的循环
for ($i =0; $i < sizeof($myArray); $i )
{
echo '<!--' . $myArray[$i] . ' --> ';
}
}
function v2($myArray = null) {
// 效率略有提高
$max = sizeof($myArray);
for ($i =0; $i < $max ; $i )
{
echo '<!--' . $myArray[$i] . ' --> ';
}
}
function v3($myArray = null){
//最佳效率
echo "<!--", implode(" --> <!--", $myArray), " --> ";
}
?>
程序输出的结果大概是这样的:
v1 ran 100 times where average exec time 0.18400 ms
v2 ran 100 times where average exec time 0.15500 ms
v3 ran 100 times where average exec time 0.09100 ms
可以看到,函数的执行时间变少,效率上升。
函数v1有个很明显的错误,每一次循环的时间,都需要调用sizeof()函数来计算。函数v2则在循环外把$myArray数组的元素个数存到$max变量中,避免了每次循环都要计算数组的元素个数,所以效率提高了。函数v3的效率最高,利用了现成的函数,避免循环。
这个例子只是给你一个感性的认识,明白什么是相对高效的代码。在实际开发中,我相信会有很多人会迷迷糊糊地写出很多低效率的代码。要把代码写得精炼而高效,恐怕需要时间去锤炼:-) 但这是另一个话题了,我们略过不谈。
数据库应用基本上每个PHP程序都会用到,在实际开发中我发现最影响整个系统效率的就是数据库这部份。

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

The default map on the iPhone is Maps, Apple's proprietary geolocation provider. Although the map is getting better, it doesn't work well outside the United States. It has nothing to offer compared to Google Maps. In this article, we discuss the feasible steps to use Google Maps to become the default map on your iPhone. How to Make Google Maps the Default Map in iPhone Setting Google Maps as the default map app on your phone is easier than you think. Follow the steps below – Prerequisite steps – You must have Gmail installed on your phone. Step 1 – Open the AppStore. Step 2 – Search for “Gmail”. Step 3 – Click next to Gmail app

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Is the clock app missing from your phone? The date and time will still appear on your iPhone's status bar. However, without the Clock app, you won’t be able to use world clock, stopwatch, alarm clock, and many other features. Therefore, fixing missing clock app should be at the top of your to-do list. These solutions can help you resolve this issue. Fix 1 – Place the Clock App If you mistakenly removed the Clock app from your home screen, you can put the Clock app back in its place. Step 1 – Unlock your iPhone and start swiping to the left until you reach the App Library page. Step 2 – Next, search for “clock” in the search box. Step 3 – When you see “Clock” below in the search results, press and hold it and

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

Are you getting "Unable to allow access to camera and microphone" when trying to use the app? Typically, you grant camera and microphone permissions to specific people on a need-to-provide basis. However, if you deny permission, the camera and microphone will not work and will display this error message instead. Solving this problem is very basic and you can do it in a minute or two. Fix 1 – Provide Camera, Microphone Permissions You can provide the necessary camera and microphone permissions directly in settings. Step 1 – Go to the Settings tab. Step 2 – Open the Privacy & Security panel. Step 3 – Turn on the “Camera” permission there. Step 4 – Inside, you will find a list of apps that have requested permission for your phone’s camera. Step 5 – Open the “Camera” of the specified app

The difference between Go language methods and functions lies in their association with structures: methods are associated with structures and are used to operate structure data or methods; functions are independent of types and are used to perform general operations.

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.
