前天看了篇文章,是关于C#的异常处理的。文中提出C#中的异常处理会对程序的执行效率产生很大影响,对于相同的一个算法,使用异常处理和使用Return返回错误的程序的时间差可以达到6s : 1s。
<?php
function getmicrotime(){
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
$time_start = getmicrotime();
class A {
public function __construct()
{
$this->display();
}
public function display()
{
throw new exception("Class A display() called.<br />");
}
}
class B extends A
{
public function __construct()
{
$this->display();
}
public function display()
{
try {
parent::display();
} catch (exception $e) {
throw new exception($e->getMessage()."Class B display() called.<br />");
}
}
}
class C extends B
{
public function __construct()
{
$this->display();
}
public function display()
{
try {
parent::display();
} catch (exception $e) {
throw new exception($e->getMessage()."Class C display() called.<br />");
}
}
}
class D extends C
{
public function __construct()
{
$this->display();
}
public function display()
{
try {
parent::display();
} catch (exception $e) {
throw new exception($e->getMessage()."Class D display() called.<br />");
}
}
}
try {
$ss = new d;
} catch(exception $e)
{
echo $e->getMessage();
}
$time_end = getmicrotime();
$time = $time_end - $time_start;
echo "Did nothing in $time seconds";
?>
<?php
function getmicrotime(){
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
$time_start = getmicrotime();
class A {
public function __construct()
{
$this->display();
}
public function display()
{
echo "Class A display() called.<br />";
return false;
}
}
class B extends A
{
public function __construct()
{
$this->display();
}
public function display()
{
if(!parent::display()) {
echo "Class B display() called.<br />";
return false;
}
}
}
class C extends B
{
public function __construct()
{
$this->display();
}
public function display()
{
if(!parent::display()) {
echo "Class C display() called.<br />";
return false;
}
}
}
class D extends C
{
public function __construct()
{
$this->display();
}
public function display()
{
if(!parent::display()) {
echo "Class D display() called.<br />";
return false;
}
}
}
$ss = new d;
$time_end = getmicrotime();
$time = $time_end - $time_start;
echo "Did nothing in $time seconds";
?>
我用php5做了个测试,结果发现php5的异常处理也会对程序运行效率产生较大的影响。
平台:winXP sp2 / apache 2.0 / php5.1
程序分别如下:
使用了exception处理








































































使用return 返回错误

































































测试结果如下:
exception处理 | return处理 | |
第一次 | 0.00075888633728s | 0.000170946121216s |
第二次 | 0.000414133071899s | 0.0001380443573s |
第三次 | 0.000410079956055s | 0.000159978866577s |
第四次 | 0.000416040420532s | 0.000160932540894s |
第五次 | 0.00037693977356s | 0.000144958496094s |
第六次 | 0.000380039215088s | 0.000140905380249s |
第七次 | 0.000383853912354s | 0.000147819519043s |