首页 > 编程技术 > php

PHP程序加速探索之代码优化

发布时间:2016-11-25 16:32

把握了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程序都会用到,在实际开发中我发现最影响整个系统效率的就是数据库这部份。

最近,我的一个老朋友向我打电话求助。他从事记者的职业有多年了,最近获得了重新出版他的很多早期专栏的权利。他希望把他的作品贴在Web上;但是他的专栏都是以纯文本文件的形式保存的,而且他既没有时间也不想去为了把它们转换成为Web页面而学习HTML的知识。由于我是他电话本里唯一一个精通计算机的人,所以他打电话给我看我是否能够帮帮他。

“让我来处理吧,”我说:“一个小时以后再给我打电话。”当然了,当他几个小时以后打电话过来,我已经为他预备好了解决的方法。这需要用到一点点PHP,而我收获了他没完没了的感谢和一箱红酒。

那么我在这一个小时里做了些什么呢?这就是本篇文章的内容。我将告诉你如何使用PHP来快速将纯ASCII文本完美地转换成为可读的HTML标记。

首先让我们来看一个我朋友希望转换的纯文本文件的例子:

Green for Mars!
John R. Doe

The idea of little green men from Mars, long a staple of science fiction, may soon turn out to be less fantasy and more fact.

Recent samples sent by the latest Mars exploration team indicate a high presence of chlorophyll in the atmosphere. Chlorophyll, you will recall, is what makes plants green. It's quite likely, therefore, that organisms on Mars will have, through continued exposure to the green stuff, developed a greenish tinge on their outer exoskeleton.

An interview with Dr. Rushel Bunter, the head of ASDA's Mars Colonization Project blah blah...

What does this mean for you? Well, it means blah blahblah...

Track follow-ups to this story online at http://www.mars-connect.dom/. To see pictures of the latest samples, log on to http://www.asdamcp.dom/galleries/220/

相当标准的文本:它有一个标题、一个署名和很多段的文字。把这篇文档转换成为HTML真正需要做的是使用HTML的分行和分段标记把原文的布局保留在Web页面上。非凡的标点符号需要被转换成为对应的HTML符号,超链接需要变得可以点击。

下面的PHP代码(列表A)就会完成上面所有的任务:

列表A

<?php
// set source file name and path
$source = "toi200686.txt";

// read raw text as array
$raw = file($source) or die("Cannot read file");

// retrieve first and second lines (title and author)
$slug = array_shift($raw);
$byline = array_shift($raw);

// join remaining data into string
$data = join('', $raw);

// replace special characters with HTML entities
// replace line breaks with <br />
$html = nl2br(htmlspecialchars($data));

// replace multiple spaces with single spaces
$html = preg_replace('/ss /', ' ', $html);

我们经常会处理来自用户输入或从数据库中读取的数据,可能在你的字符串中有多余的空白或制表符,回车等。存储这些额外的字符是有点浪费空间的。

假如您想要去掉字符串开始和结束的空白可以使用PHP内部函数trim() 。但是, 我们经常想完全清除空白。需要把开始和结束的空白清除掉,将多个空白变为一个空白,使用一个规则来处理同样的类型的其它空白。

完成这些可以使用PHP的正则表达式来完成

下例可以去除额外Whitespace

<?php
$str = " This line containstliberal rn use of whitespace.nn";

// First remove the leading/trailing whitespace
//去掉开始和结束的空白
$str = trim($str);

// Now remove any doubled-up whitespace
//去掉跟随别的挤在一块的空白
$str = preg_replace('/s(?=s)/', '', $str);

// Finally, replace any non-space whitespace, with a space
//最后,去掉非space 的空白,用一个空格代替
$str = preg_replace('/[nrt]/', ' ', $str);

// Echo out: 'This line contains liberal use of whitespace.'
echo "<pre>{$str}</pre>";
?>


上例一步一步的去掉所有的空白。首先我们使用trim()函数来去掉开始和结束的空白。然后,我们使用preg_replace() 去除重复的。s代表任何whitespace 。(?=) 表示向前查找 。它味着只匹配后面有和它本身相同字符的字符。所以这个正则表达式的意思是: "被whitespace 字符跟随的任何whitespace 字符。" 我们用空白来替换掉,这样也就去除了,留下的将是唯一的whitespace 字符。

最后, 我们使用另一个正则表达式[nrt]来查找任何残余的换行符(n), 回车(r), 或制表符(t) 。我们用一个空格来替换这些。

利用php的socket编程来直接给接口发送数据来模拟post的操作。

<?
/***********************************************************
Name: POST 测试程序 Vesion: 1.0 Date: 2004-08-05 ************************************************************/
/ $flag = 0;
//要post的数据
$argv = array(
'var1'=>'abc',
'var2'=>'你好吗');
//构造要post的字符串
foreach ($argv as $key=>$value) {
if ($flag!=0) {
$params .= "&";
$flag = 1;
}
$params.= $key."="; $params.= urlencode($value);
$flag = 1;
}
$length = strlen($params);
//创建socket连接
$fp = fsockopen("127.0.0.1",80,$errno,$errstr,10) or exit($errstr."--->".$errno);
//构造post请求的头
$header = "POST /mobile/try.php HTTP/1.1rn";
$header .= "Host:127.0.0.1rn";
$header .= "Referer:/mobile/sendpost.phprn";
$header .= "Content-Type: application/x-www-form-urlencodedrn";
$header .= "Content-Length: ".$length."rn";
$header .= "Connection: Closernrn";
//添加post的字符串
$header .= $params."rn";
//发送post的数据
fputs($fp,$header);
$inheader = 1;
while (!feof($fp)) {
$line = fgets($fp,1024); //去除请求包的头只显示页面的返回数据
if ($inheader && ($line == "n" || $line == "rn")) {
$inheader = 0;
}
if ($inheader == 0) {
echo $line;
}
}
fclose($fp);
?>

查看 POP3/SMTP 协议的时候想尝试一下自己写一个操作类,核心没啥,就是使用 fsockopen ,然后写入/接收数据,只实现了最核心的部分功能,当作是学习 Socket 操作的练手。其中参考了 RFC 2449和一个国外的简单Web邮件系统 Uebimiau 的部分代码,不过绝对没有抄他滴,HOHO,绝对原创。假如你喜欢,请收藏,随便修改,嗯,但是记得不要删除偶类里的声名,究竟偶也是辛辛劳苦写了好几天呐。
另外,欢迎自由发挥,改善或者修正这个类,希望能够为你所用。代码没有认真仔细的调试,发现bug请自己修正,HOHO!

<?php
/**
* 类名:SocketPOPClient
* 功能:POP3 协议客户端的基本操作类
* 作者:heiyeluren <http://blog.111cn.net/heiyeshuwu>
* 时间:2006-7-3
* 参考:RFC 2449, Uebimiau
* 授权:BSD License
*/

class SocketPOPClient
{
var $strMessage = '';
var $intErrorNum = 0;
var $bolDebug = false;

var $strEmail = '';
var $strPasswd = '';
var $strHost = '';
var $intPort = 110;
var $intConnSecond = 30;
var $intBuffSize = 8192;

var $resHandler = NULL;
var $bolIsLogin = false;
var $strRequest = '';
var $strResponse = '';
var $arrRequest = array();
var $arrResponse = array();


//---------------
// 基础操作
//---------------

//构造函数
function SocketPOP3Client($strLoginEmail, $strLoginPasswd, $strPopHost='', $intPort='')
{
$this->strEmail = trim(strtolower($strLoginEmail));
$this->strPasswd = trim($strLoginPasswd);
$this->strHost = trim(strtolower($strPopHost));

if ($this->strEmail=='' || $this->strPasswd=='')
{
$this->setMessage('Email address or Passwd is empty', 1001);
return false;
}
if (!preg_match("/^[w-] (.[w-] )*@[w-] (.[w-] ) $/i", $this->strEmail))
{
$this->setMessage('Email address invalid', 1002);
return false;
}
if ($this->strHost=='')
{
$this->strHost = substr(strrchr($this->strEmail, "@"), 1);
}
if ($intPort!='')
{
$this->intPort = $intPort;
}
$this->connectHost();
}

//连接服务器
function connectHost()
{
if ($this->bolDebug)
{
echo "Connection ".$this->strHost." ...rn";
}
if (!$this->getIsConnect())

标签:[!--infotagslink--]

您可能感兴趣的文章: