我一直是一个写干净可读的代码的人。尽管如此,我仍然无法确定在使用或多或少的<?php
标记时,在处理速度上是否存在任何差异。下面是一些比较代码:
首选代码:
<?php while($condition): ?>
<?php if($anotherCondition): ?>
Hello world!
<?php endif; ?>
<?php endwhile; ?>
较短代码:
<?php while($condition):
if($anotherCondition): ?>
Hello world!
<?php endif;
endwhile; ?>
在第二段代码中,我只使用了两个<?php
标记,但是我发现第一个代码块更容易理解。因为我使用了更多的<?php
标签,所以效率下降了吗?
发布于 2013-01-25 00:05:10
这对性能有影响,但很可能可以忽略不计。任何不在<?php ?>
块内的空间或选项卡都将作为PHP输出的一部分发送。要理解这一点,请考虑以下简单的示例:
PHP代码:
<?php while($condition): ?>
<?php if($anotherCondition): ?>
Hello world!
<?php endif; ?>
<?php endwhile; ?>
被发送到电线上,如
\n
\t\n
\t\tHello world!\n
\t\n
\n
而这个PHP:
<?php while($condition):
if($anotherCondition): ?>
Hello world!
<?php endif;
endwhile; ?>
返回以下内容:
\n
\t\tHello world!\n
\n
不过,这并不是你真正想要担心的事情,我说的是去读可读的代码。不过,我要说的是,您的第一个示例需要大量额外的输入,您确定这样做更好吗?
发布于 2013-01-24 23:59:59
没有语法问题会影响性能,所以编写可读的代码:)
您的第二个示例也是可读的,没有理由使用4而不是2 php块。
发布于 2013-01-25 02:13:42
我测试了您的2种代码+1无空间版本,通过在代码前引入$time_start = microtime(true);
和代码后引入echo $time = microtime(true) - $time_start;
来检查处理速度。
由于处理时间接近微秒,结果可能因许多微小因素而异。因此,我测试了每段代码10次,并做了一个平均时间。
用打印文本进行测试
优先使用代码
<?php $time_start = microtime(true); ?>
<?php $i = 0; ?>
<?php while($i <= 5000): ?>
<?php echo $i; ?>
<?php $i++; ?>
<?php if($i == 5000): ?>
This is the end!
<?php endif; ?>
<?php endwhile; ?>
<?php echo $time = microtime(true) - $time_start; ?>
平均时间: 0.00366528034210207秒
短码
<?php
$time_start = microtime(true);
$i = 0;
while($i <= 5000):
echo $i." ";
$i++;
if($i == 5000):
echo "This is the end!";
endif;
endwhile;
echo $time = microtime(true) - $time_start;
?>
平均时间: 0.00243649482727052秒
空间-无空间代码
<?php $time_start=microtime(true);$i=0;while($i<=5000):echo $i." ";$i++;if($i==5000):echo "This is the end!";endif;endwhile;echo$time=microtime(true)-$time_start;?>
平均时间: 0.00242624282836913秒
没有打印文本的测试
优先使用代码
<?php $time_start = microtime(true); ?>
<?php $i = 0; ?>
<?php while($i <= 5000): ?>
<?php $i++; ?>
<?php if($i == 5000): ?>
<?php $a=$i; ?>
<?php endif; ?>
<?php endwhile; ?>
<?php echo $time = microtime(true) - $time_start; ?>
平均时间: 0.00143785476684571秒
短码
<?php
$time_start = microtime(true);
$i = 0;
while($i <= 5000):
$i++;
if($i == 5000):
$a=$i;
endif;
endwhile;
echo $time = microtime(true) - $time_start;
?>
平均时间: 0.000472831726074218秒
空间-无空间代码
<?php $time_start=microtime(true);$i=0;while($i<=5000):;$i++;if($i==5000):$a=$i;endif;endwhile;echo$time=microtime(true)-$time_start;?>
平均时间: 0.000457286834716797秒
结论/摘要
带有打印文本的
首选代码: 0.00366528034210207秒
较短的代码: 0.00243649482727052秒(比以前快33.5%)
无空间代码: 0.00242624282836913秒(比以前快0.4%)
不打印文本
首选代码: 0.00143785476684571秒
较短的代码: 0.000472831726074218秒(比以前快66.1%)
无空间代码: 0.000457286834716797秒(比以前快3.3%)
平均10倍是不正确的。它应该做100或1000次,删除极值的结果,以获得一个相当好的表示。但是通过这个简单的例子,我们可以看到两个第一个代码之间的显着差异,第三个代码是没有意义的。
https://stackoverflow.com/questions/14513061
复制相似问题