search
Homephp教程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程序都会用到,在实际开发中我发现最影响整个系统效率的就是数据库这部份。至于数据库的优化和数据查询语句的优化,在此限于篇幅不详细讨论。读者可参考《MySQL查询优化技术讲座》



Statement
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

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.