编写此代码的哪种方式效率最高?

时间:2012-01-19 17:25:12

标签: php html

如果我在大量的PHP代码中,而不是从PHP中出来,我通常会编写包含如下变量的代码:

echo "This is how I use a ".$variable." inside a string";

但实际上脱离PHP更有效率:

?>

Should I instead use the <? echo $variable; ?> like this

<? // then back into PHP

在整个页面中,会有很多像这样的代码实例,因为我用动态内容填充页面,或者这是否过于泛化?

6 个答案:

答案 0 :(得分:5)

我只建议在回显HTML时跳出php标签,而不仅仅是字符串。

这对于一个字符串来说很好:

// You don't need to concat, double quotes interpolate variables
echo "This is how I use a $variable inside a string";

但对于HTML,我个人喜欢这样做:

<?php //... ?>
<div>
    <span>This is how I use a <?=$variable?> inside HTML</span>
</div>
<?php //... ?>

答案 1 :(得分:1)

使用echo似乎稍快一些。我制作了这个简单的基准脚本:

<?php
$variable = "hello world";
$num = 10000;
$start1 = microtime(true);
for ($i = 0; $i<$num;$i++) {    
    echo "test " . $variable . " test\n";    
}
$time1 = microtime(true) - $start1;
$start2 = microtime(true);
for ($i = 0; $i<$num;$i++) {
    ?>test <?php echo $variable;?> test
<?
}
$time2 = microtime(true) - $start2;
echo "\n$time1\n$time2\n";

echo循环持续快了约25%。

实际上,这种差异非常小,除非你真的在做数百万个这样的输出语句,否则不会对整体性能产生任何影响。我仍然建议使用echo只是因为它更简单易读。

答案 2 :(得分:0)

echo 'This is how I use a'.$variable.' inside a string';可能是效率最高的..

在第一种情况下,您正在使用",这会导致整个字符串被评估为内联变量。

在你的第二种情况下,我认为翻译的上下文切换比我的样本要贵一些。

话虽如此,无论如何,你都会看到微不足道的差异。

答案 3 :(得分:0)

是的,只需在您需要的非PHP(HTML)之间使用<?php ..... ?>即可。你甚至可以在其中使用for-while循环。

答案 4 :(得分:0)

另一种方法是使用printf(),如下所示:

// your variable
$my_variable = "Stack Overflow";

printf("Real programmers graduate on %s", $my_variable);

// this prints 'Real programmers graduate on Stack Overflow, 

Plus还有额外的好处,不需要经常连接。 但是,与echo语句

相比,可能值得了解它的执行情况

答案 5 :(得分:0)

在大多数情况下,建议不要使用php的短标签。在任何情况下,如果你在双引号内,你甚至不必使用concat点来输出变量。你可以这样做:

echo "This is how I use a $variable inside a string";

或者这个:

echo "This is how I use a {$variable} inside a string";

第二个示例允许表达式(数组元素和对象属性)由花括号分隔。您也可以在第一个示例中使用它们,但变量解析的贪婪有时会导致问题。使用花括号可以阻止它。