性能:
很容易测试。如果您正在做机器学习或大数据之类的事情,那么您应该真正查看的是编译或组装而不是解释的东西;如果周期真的很重要。 Here are some benchmarks between the various programming languages. 看起来 do-while 循环是我系统上使用 PHP 的赢家。
$my_var = "some random phrase";
function fortify($my_var){
for($x=0;isset($my_var[$x]);$x++){
echo $my_var[$x]." ";
}
}
function whilst($my_var){
$x=0;
while(isset($my_var[$x])){
echo $my_var[$x]." ";
$x++;
}
}
function dowhilst($my_var){
$x=0;
do {
echo $my_var[$x]." ";
$x++;
} while(isset($my_var[$x]));
}
function forstream(){
for($x=0;$x<1000001;$x++){
//simple reassignment
$v=$x;
}
return "For Count to $v completed";
}
function whilestream(){
$x=0;
while($x<1000001){
$v=$x;
$x++;
}
return "While Count to 1000000 completed";
}
function dowhilestream(){
$x=0;
do {
$v=$x;
$x++;
} while ($x<1000001);
return "Do while Count to 1000000 completed";
}
function dowhilestream2(){
$x=0;
do {
$v=$x;
$x++;
} while ($x!=1000001);
return "Do while Count to 1000000 completed";
}
$array = array(
//for the first 3, we're adding a space after every character.
'fortify'=>$my_var,
'whilst'=>$my_var,
'dowhilst'=>$my_var,
//for these we're simply counting to 1,000,000 from 0
//assigning the value of x to v
'forstream'=>'',
'whilestream'=>'',
'dowhilestream'=>'',
//notice how on this one the != operator is slower than
//the < operator
'dowhilestream2'=>''
);
function results($array){
foreach($array as $function=>$params){
if(empty($params)){
$time= microtime();
$results = call_user_func($function);
} elseif(!is_array($params)){
$time= microtime();
$results = call_user_func($function,$params);
} else {
$time= microtime();
$results = call_user_func_array($function,$params);
}
$total = number_format(microtime() - $time,10);
echo "<fieldset><legend>Result of <em>$function</em></legend>".PHP_EOL;
if(!empty($results)){
echo "<pre><code>".PHP_EOL;
var_dump($results);
echo PHP_EOL."</code></pre>".PHP_EOL;
}
echo "<p>Execution Time: $total</p></fieldset>".PHP_EOL;
}
}
results($array);
标准: while、for 和 foreach 是大多数人在 PHP 中使用的主要控制结构。在我的测试中,do-while 比 while 快,但在网络上的大多数 PHP 编码示例中基本上没有得到充分利用。
for 是计数控制的,所以它会迭代特定的次数;虽然我自己的结果比使用while 来做同样的事情要慢。
while 非常适合以 false 开头的东西,因此它可以防止某些东西运行并浪费资源。
do-while 至少一次,然后直到条件返回false。在我的结果中,它比 while 循环快一点,但它至少会运行一次。
foreach 非常适合遍历array 或object。即使您可以使用数组语法通过 for 语句循环字符串,但在 PHP 中却不能使用 foreach 来执行此操作。
控制结构嵌套:这真的取决于你在做什么来确定嵌套时使用的控制结构。在某些情况下,例如面向对象编程,您实际上希望(单独)调用包含您的控制结构的函数,而不是使用包含许多嵌套控件的过程风格的大量程序。这可以使其更易于阅读、调试和实例化。