php
2011-04-03 79 views -1 likes 
-1

我有兩個頁面:哪一個更快?單獨的HTML還是嵌入在PHP中?

的index.php:

<?php 
    $mtime = microtime(); 
    $mtime = explode(" ",$mtime); 
    $mtime = $mtime[1] + $mtime[0]; 
    $starttime = $mtime; 
    $text = ' 
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>Untitled Document</title> 
    </head> 
     <body> 
     html content 
     </body> 
    </html>'; 
    echo $text; 
    $mtime = microtime(); 
    $mtime = explode(" ",$mtime); 
    $mtime = $mtime[1] + $mtime[0]; 
    $endtime = $mtime; 
    $totaltime = ($endtime - $starttime); 
    echo "This page was created in ".$totaltime." seconds"; 
?> 

和index2.php:

<?php 
    $mtime = microtime(); 
    $mtime = explode(" ",$mtime); 
    $mtime = $mtime[1] + $mtime[0]; 
    $starttime = $mtime; 
?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 
</head> 

<body> 
<?php echo 'html content'; ?> 
</body> 
</html> 
<?php 
    $mtime = microtime(); 
    $mtime = explode(" ",$mtime); 
    $mtime = $mtime[1] + $mtime[0]; 
    $endtime = $mtime; 
    $totaltime = ($endtime - $starttime); 
    echo "This page was created in ".$totaltime." seconds"; 
?> 

的index.php的測試結果:

html content This page was created in 6.1988830566406E-5 seconds 

和index2.php:

html contentThis page was created in 6.4849853515625E-5 seconds 

爲什麼嵌入PHP的HTML比index2.php更快?

+0

的index.php是非常非常無用 – Eray 2011-04-03 20:09:42

+10

這不是測量程序的性能,除非你這個平均超過數千奔跑的正確方法。即使如此,由於您生成的HTML是微不足道的,所以它不太可能重要。 – 2011-04-03 20:09:44

+1

這裏看不到太多的速度 – fazo 2011-04-03 20:09:54

回答

10

這不是一個真正的答案,但我不得不想知道爲什麼你認爲這很重要? (如果你擔心優化事情到了這個水平,那麼我懷疑PHP可能不是理想的語言。)

從本質上說,代碼的可讀性,一致性和任何將有助於長期的維護是方式更多比這樣的微觀優化更重要,如果您遇到性能問題,我很樂意將大量資金投入到這樣一個事實上,即不會有任何事情要做HTML的輸出/無論是否彈出和在PHP代碼中出現了很多阻塞。因此,如果您遇到性能問題,請查看代碼以找出問題所在 - 不要浪費時間擔心什麼是「最佳」 - 在這種情況下,「最佳」解決方案是最簡單的方法從事該項目的程序員。

+0

我想以正確的方式走路,而不是我們的開發人員展示給我...... – utopia 2011-04-03 20:21:49

+2

這是完美的,唯一可能的答案。沒有規則說回答應該只是文字和積極的。 – 2011-04-03 20:23:19

+1

@utopia - 效率不是選擇採取哪條路徑的最佳方式。問題應該是:*「我最舒適的工作方式」*和*「最適合我目前情況的技術」*。如果你花費了很長時間來忙於諸如2.9E-6時差之類的事情,那麼你將不會得到任何實際的編碼。在你的例子中,我會選擇第二個代碼示例,只是爲了讓你更輕鬆地編輯代碼而不用擔心引號等。 – 2011-04-03 20:35:54

0

我認爲這是由php和html模式之間的切換造成的。

但在運行時間沒有significal區別...

相關問題