<?php
/**
* 本模块演示一些常见的代码习惯优化
* @author www.phpchengdu.com php成都培训中心 罗维
*/
set_time_limit(0);
echo "把初值计算放在循环外:<br />";
echo "优化前:";
$array=array("1"=>"a","2"=>"b","3"=>"c");
$s=microtime(true);
for($i=0;$i<10000;$i++){
for($j=0;$j<count($array);$j++){
}
}
echo microtime(true)-$s;
echo "<br>";
echo "优化后:";
$array=array("1"=>"a","2"=>"b","3"=>"c");
$s=microtime(true);
$length=count($array);
for($i=0;$i<10000;$i++){
for($j=0;$j<$length;$j++){
}
}
echo microtime(true)-$s;
echo "<br>";
echo "把最容易出现的条件判断放在前面:<br />";
echo "优化前:";
$s=microtime(true);
for($i=0;$i<10000;$i++){
$score[i]=rand(0,100);
$gender[i]=rand(0,1)=='0'?'男':'女';
}
for($i=0;$i<10000;$i++){
if($score[i]>90 and $gender[i]=='男'){
}
}
echo microtime(true)-$s;
echo "<br>";
echo "优化后:";
$s=microtime(true);
for($i=0;$i<10000;$i++){
if($gender[i]=='男' and $score[i]>90){
}
}
echo microtime(true)-$s;
echo "<br>";
echo "减少包含文件数量";
echo "<br>";
echo "优化前:";
$s=microtime(true);
for($i=0;$i<100;$i++){
require_once("include_file.php");
}
echo microtime(true)-$s;
echo "<br>";
echo "优化后:";
$s=microtime(true);
for($i=0;$i<10;$i++){
require_once("include_file.php");
}
echo microtime(true)-$s;
echo "<br>";
echo "如果仅是提供一些常用的方法程序供不同的模块调用,则使用静态成员函数,不要去实例化后才使用";
echo "<br>";
echo "优化前:";
$s=microtime(true);
for($i=0;$i<1000;$i++){
$myLibrary=new myLibrary();
$myLibrary->add();
}
echo microtime(true)-$s;
echo "<br>";
echo "优化后:";
$s=microtime(true);
for($i=0;$i<100;$i++){
myLibrary::add1();
}
echo microtime(true)-$s;
echo "<br>";
echo "有封装好的就用封装好的功能,尽量不要自己去实现";
echo "<br>";
echo "优化前:";
$s=microtime(true);
for($i=0;$i<100;$i++){
$fp=fopen("sample.txt","r");
while (!feof($fp)){
$content=$content.fread($fp,1024);
}
fclose($fp);
}
echo microtime(true)-$s;
echo "<br>";
echo "优化后:";
$s=microtime(true);
for($i=0;$i<100;$i++){
$content=file_get_contents("sample.txt");
}
echo microtime(true)-$s;
echo "<br>";
class myLibrary{
public function add(){
$a=1+1;
}
public static function add1(){
$a=1+1;
}
}

