工欲善其事必先利其器,作为一名合格的PHP开发工程师,应该尽可能的让自己的代码更加高效。本篇简单的提供了一些PHP代码优化方面的建议。旨在共同进步。
php经济性
经济性取决于PHP脚本,不同PHP脚本其经济性也会不同,简单而言就是尽量避免一些无效的函数调用,简化函数调用流程。因为函数调用越多,PHP脚本的响应时间就会越长。
提前计算循环长度
错误实例
<?php
$arr = array(1,2,3,4,5,6,7,8,9,10);
for($i = 0;$i<count($arr);$i++){
echo $arr[$i];
}
首先我们来分析一下这段代码
初始化 索引变量 $i为0,并进行加1操作,期间通过 count() 检查数组长度,总共调用10次count,按经济性 调用越多,耗时越长的原则这是有问题的。总共这里有9次是属于多余调用。为此我们将其优化如下,优化后我们仅需调用一次count()
<?php
$arr = array(1,2,3,4,5,6,7,8,9,10);
$count = count($arr);
for($i = 0;$i<$count;$i++){
echo $arr[$i];
}
优化完成后我们做一下性能对比、先看优化前代码执行占用时间(为了效果更明显,我们这里循环100万次)
<?php
$arr = array(1,2,3,4,5,6,7,8,9,10);
$begin_time = microtime(true);
for($j = 0;$j<100000;$j++)
{
for($i = 0;$i<count($arr);$i++){
}
}
echo(microtime(true) - $begin_time);
优化后的代码
<?php
$arr = array(1,2,3,4,5,6,7,8,9,10);
$count = count($arr);
$begin_time = microtime(true);
for($j = 0;$j<100000;$j++)
{
for($i = 0;$i<$count;$i++){
}
}
echo(microtime(true) - $begin_time);
分别执行十次计算平均值
类型 | 平均耗时 |
---|---|
循环前计算长度 | 0.032001 |
循环中计算长度 | 0.043003 |
可以看出在性能上还是有些许的提升
使用 foreach 代替 for while循环遍历数组元素
以下三段代码创建了一个包含100万元素的数组$items,每个元素的值都为12345678910,之后采用foreach,for,while循环遍历每个元素,然后分别统计出所需的消耗时间
foreach方式
<?php
$items = array_fill(0,1000000,'1234567910');
$begin_time = microtime(true);
foreach($items as $item){
$x = $item;
}
echo microtime(true) - $begin_time;
while方式
<?php
$items = array_fill(0,1000000,'1234567910');
$begin_time = microtime(true);
$i = 0;
while($i<1000000){
$x = $items[$i];
$i++;
}
echo microtime(true) - $begin_time;
for
<?php
$items = array_fill(0,1000000,'1234567910');
$begin_time = microtime(true);
for($i =0;$i<1000000;$i++){
$x = $items[$i];
}
echo microtime(true) - $begin_time;
性能比对
方法 | 平均耗时 |
---|---|
foreach | 0.018001 |
while | 0.035001 |
for | 0.034001 |
更快的访问对象
前言:
本节所书写的内容违背了常规面向对象编程逻辑,但由于在性能上可以得到较大的提升,所以在这里还是提一下。各位可根据自己项目的实际需要来决定如何利用。
以下为使用了封装的USER类,包含了name 和 age 私有成员变量。通过接口获取和设置对应的值。
同样,我们循环了百万次获取USER中的NAME值。以便接下来做性能对比
<?php
class User{
private $name = "jiesen";
private $age = '30';
function getName(){
return $this->name;
}
function getAge(){
return $this->age;
}
function setName($name){
$this->name = $name;
}
function setAge($age){
$this->age = $age;
}
}
$user = new \User();
$begin_time = microtime(true);
for($i = 0;$i<1000000;$i++){
$user->getName();
}
echo microtime(true) - $begin_time;
以下代码为直接读取类的成员变量
<?php
class User{
public $name = "jiesen";
public $age = '30';
}
$user = new \User();
$begin_time = microtime(true);
for($i = 0;$i<1000000;$i++){
$user->name;
}
echo microtime(true) - $begin_time;
性能对比
类型 | 耗时 |
---|---|
使用了封装 | 0.108006 |
直接调用 | 0.054003 |
先写到这,