性能沒有性能上的差異: 很容易的去測試。如果你正在做一些類似機器學習或大數據的事情,你應該看看編譯的或彙編的而不是解釋的儘管;如果週期真的的問題。 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
語句來循環一個字符串,但是你不能使用foreach來通過PHP來完成它。
控制結構嵌套:這真的取決於你在做什麼決定,同時控制結構嵌套時使用。在一些像面向對象編程的情況下,你實際上需要調用包含你的控制結構(單獨)的函數,而不是使用包含許多嵌套控件的過程風格的大規模程序。這可以使讀取,調試和實例化更容易。
性能無關緊要。 –
在風格上,增量式for循環很少用於在PHP中迭代數組。通常使用'foreach',因爲它可以在循環內提供數組鍵和值。 –