<?php
function a() //平均0.00275
{
$a = 'aa';
return $a;
}
class dbff //平均0.00111
{
var $a = 'aa';
function a()
{
return $this->a;
}
}
$c = new dbff(); //test
$time_start = microtime();
for($i=0; $i<1000; $i++){
echo a();
//echo $c->a();
}
$time_last = microtime();$time = $time_last - $time_start;
echo '<br /> spend to time :'.$time;
?>
{
$a = 'aa';//这里就是用多的时间。要是你直接return 'aa';时间就会不同了
return $a;
}
class dbff //平均0.00111
{
var $a = 'aa';
function a()
{
return $this->a;
}
}
一个你在函数里面有赋值,另外一个函数里面没有赋值。
就是这么一点差别
function func(){
$str = 'a string';
return $str;
}
class M {
var $a = 'aa';
function m() {
$str = 'a string';
return $str;
}
}
/**
* test case
*/
$m = new M();
$time_start = microtime(true);
for($i=0; $i<10000; $i++){
// func();
$m->m();
}
/**
* Function
* 10,000
* 0.012238025665283
* 0.010669946670532
* 0.011427879333496
* Method
* 10,000
* 0.014846086502075
* 0.013679981231689
* 0.012878894805908
*/
$time = microtime(true) - $time_start;
echo 'Elapsed :' . $time;
//echo PHP_VERSION; // 5.2.5
?>差别不是很明显,但function还是要快一些。你那个测试显然是有问题的。变量作用域不同,访问速度肯定是有差别的。
<?php$a = "aa";
function a($a = '')
{
//$a = 'aa'; return $a; //平均0.00275
//global $a; return $a; //平均0.00298
//return $GLOBALS['a']; //平均0.002705 函数头没参数可达 0.002000
//return $a; //平均0.00245 传参
}
class ccc //平均0.00230
{
var $a = 'aa';
function a()
{
return $this->a;
}}
$c = new ccc(); //test
$time_start = microtime();
for($i=0; $i<1000; $i++){
echo a();
// echo $c->a();
}
$time_last = microtime();$time = $time_last - $time_start;
echo '<br /> spend to time :'.$time;
?>
这里最新的数据, 顺便总结一下:to 8楼 这样测试没意义, 没人会在方法内赋值, 再返回的, 方法返回的只是属性, 或过滤的参数返回.
一 从理论上来说函数和方法一样快, 但从使用角度来说, 是方法快.
二 函数里最好用$GLOBALS, 或传参