Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6942276
  • 博文数量: 701
  • 博客积分: 10821
  • 博客等级: 上将
  • 技术积分: 12021
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-02 10:41
个人简介

中科院架构师,专注企业数字化各个方面,MES/ERP/CRM/OA、物联网、传感器、大数据、ML、AI、云计算openstack、Linux、SpringCloud。

文章分类

全部博文(701)

分类: PHP

2015-08-08 20:01:53


原文摘自:http://orangeholic.iteye.com/blog/1763937

1.用逗号连接echo字符串
  1. $name='orange';  
  2. $address='BeiJing';  
  3. echo 'Hi,'.$name.'! Welcome to '.$address;//慢  
  4. echo 'Hi,',$name,'! Welcome to ',$address;//快,建议方式  
原因可以查看两者的opcode,用逗号的方式和用点号方式的opcode如下

2.使用require还是require_once
   老问题了,Lerdof N年前就提出来了,建议用require,因为require_once发起少量的stat调用,我们可以通过ab来测试一下效率
#a.php文件
  1. require_once('ClassA.php');  
  2. require_once('ClassB.php');  
  3. require_once('ClassC.php');  
  4. echo 'end'
测试ab -c 10 -n 10000 同时10个请求共请求10000次,结果如下:

#b.php文件
  1. require('ClassA.php');  
  2. require('ClassB.php');  
  3. require('ClassC.php');  
  4. echo 'end';  
同样测试测试ab -c 10 -n 10000 同时10个请求共请求10000次,结果如下:

增加了近20的并发量!

3.提前计算循环长度
如下代码
  1. $items=array(0,1,2,3,4,5,6,7,8,9);  
  2. for($i=0;$i<count($items);$i++)  
  3. {  
  4.      $temp=$items[$i]*$items[$i];  
  5. }  

循环是如何执行的?
* $i初始化0,调用count($items)检测,平方;
* $i等于1,调用count($items)检测,平方;
* $i等于2,调用count($items)检测,平方;
* ...........................
count($items)执行了count($items)遍!所以我们提前计算循环长度,实验对比
#a.php文件
  1. $start=microtime(true);  
  2. $items=array_fill(0,100000,'orange');  
  3. for($i=0;$i<count($items);$i++)  
  4. {  
  5.      $temp=$items[$i].$items[$i];  
  6. }  
  7. echo microtime(true)-$start;  

执行结果:
  1. $start=microtime(true);  
  2. $items=array_fill(0,100000,'orange');  
  3. $count=count($items);  
  4. for($i=0;$i<$count;$i++)  
  5. {  
  6.      $temp=$items[$i].$items[$i];  
  7. }  
  8. echo microtime(true)-$start;  

执行结果:
foreach    0.0078毫秒 while   0.0099毫秒 for   0.0105毫秒
5.勿要追求极致的面向对象
面向对象虽然有各种好处,但效率损失是个硬伤。
#a.php文件
  1. /** 
  2. *  属性private,get/set齐全 
  3. */  
  4. class Student{  
  5.     private $name;  
  6.     private $age;  
  7.     public function setAge($age){  
  8.         $this->age = $age;  
  9.     }  
  10.     public function getAge(){  
  11.         return $this->age;  
  12.     }  
  13.     public function setName($name){  
  14.         $this->name = $name;  
  15.     }  
  16.     public function getName(){  
  17.         return $this->name;  
  18.     }  
  19. }  
  20.   
  21. $student=new Student();  
  22. $start=microtime(true);  
  23. for($i=0;$i<100000;$i++){  
  24.     $student->setAge($i);  
  25. }  
  26. echo microtime(true)-$start;  

执行时间
  1. /** 
  2. *  属性public,直接赋值属性 
  3. */  
  4. class Student{  
  5.     public  $name;  
  6.     public  $age;  
  7. }  
  8. $student=new Student();  
  9. $start=microtime(true);  
  10. for($i=0;$i<100000;$i++){  
  11.     $student->age=$i;  
  12. }  
  13. echo microtime(true)-$start;  

管理员在2009年8月13日编辑了该文章文章。
-->
阅读(7771) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~