Static method efficiency test code in PHP class

  • 2020-03-31 21:09:13
  • OfStack

Class is defined as follows:
 
class test 
{ 
public static function a(){} 
public function b(){} 
} 
$obj = new test; 

Compare the following situations
The test: : (a);
$obj - > (a);
$obj - > (b);
Test code:
 
$obj = new test; 
$test_times = 100; 
$times = 10000; 
$effi1 = array(); 
$effi2 = array(); 

while ($test_times-- > 0) 
{ 
$time1 = microtime(true); 
for($i=0; $i<$times; $i++) 
{ 
test::a(); 
} 
$time2 = microtime(true); 
for($i=0; $i<$times; $i++) 
{ 
$obj->a(); 
} 
$time3 = microtime(true); 
for($i=0; $i<$times; $i++) 
{ 
$obj->b(); 
} 
$time4 = microtime(true); 
$effi1[] = ($time3 - $time2) / ($time2 - $time1); 
$effi2[] = ($time4 - $time3) / ($time3 - $time2); 
} 
echo avg($effi1),"n",avg($effi2); 

The final avg is a custom function to calculate the average:
 
function avg($arr) 
{ 
$result = 0; 
foreach ($arr as $val) 
{ 
$result += $val; 
} 
$result /= count($arr); 
return $result; 
} 

Program output result:
 
PHP 5.2.14 
view sourceprint?1 0.76490628848091 
2 1.0699484376399 
view sourceprint?1 PHP 5.3 
view sourceprint?1 0.56919482299058<BR>1.1016495598611 

Repeat execution. 10) all of them are similar to this result, indicating that:
1. Accessing static methods directly by class name is 76% as efficient as accessing static methods by instance, or even 56% with PHP5.3
2. The efficiency of accessing static methods through instances is 106 times that of accessing non-static member methods, which became 110% in version 5.3
3. Assuming that the efficiency of accessing static methods by class name is not reduced when PHP is upgraded from 5.2 to 5.3, the efficiency of accessing functions by instance is increased by at least 35%. I haven't read the PHP source code, and those of you who have studied the PHP source code would like to be able to tell me if this hypothesis is true (I think it is).
Note: the above test is based on Windows 7 and php.exe, 5.2.14 USES apache2.2 test results are no different, considering that php.exe and web access through the execution of the PHP core is the same, so 5.3 lazy to change the server configuration, the results should be the same.

Related articles: