php性能优化少被注意的部分

下面内容来源于网络和Pro PHP  Application Performance

1、使用require vs require_once

参考:http://www.laruence.com/2012/09/12/2765.html

require  is faster than  require_once due to the high number of operational stat calls 
made when importing the PHP script. If the file you requested is located within the 
directory /var/shared/htdocs/myapp/models/MyModels/ClassA.php , the operating system 
will make a stat call within each of the directories before it reaches  ClassA.php. In this 
example, that is a total of six stat calls. While  require  also issues  stat calls, they are fewer 
in number. So, the fewer func tion calls there are, the fa ster your code becomes.  

require比require_once 更快 是由于在导入php 脚本的时候的大量stat操作导致的。如果请求一个在/var/shared/htdocs/myapp/models/MyModels/ClassA.php这个地址的文件时,在达到ClassA.php前,操作系统将对每一个directories做一次stat调用。require_once需要6次调用。require也是有stat调用,但是在数量上更少,因此,使用它有更少的函数调用,也就更快


2、使用"comma"代替“period”

<?php 
echo "Hi "."there. "."how are "."you?";  //Slow 
echo "Hi ","there. ","how are ","you?";  //Faster…slightly 


3、遍历数组,foreach最快,while和for次之

 插曲:未优化代码

<?php  
$items = array(1,2,3,4,5,6,7,8,9,10); 
for($i=0; $i<count($items); $i++) 
{ 
   $x = 10031981 * $i;   
}

这个代码将count($items)移出来,减少函数调用和计算,效率更高

for,foreach,while代码,最高效的foreach,原因这里就不找了

<?php  
$items = array_fill(0, 100000, '12345678910'); 
 
$start = microtime(); 
reset($items); 
foreach($items as $item) 
{ 
   $x = $item; 
} 
echo microtime()-$start; 

4、fread在读小文件时更快,file_get_contents读大文件时更快,具体多大文件是中间线,自己可以根据环境测试下

5、读取类属性,将类属性设置为public,直接读取最快,原因就不说了,你懂的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值