[英]__callStatic vs static function of PHP
使用PHP的魔術函數__callStatic和正常定義靜態函數之間在性能上有什么區別。
例:
class Welcome{
public static function __callStatic($method, $parameters){
switch ($method) {
case 'functionName1':
// codes for functionName1 goes here
break;
case 'functionName2':
// codes for functionName2 goes here
break;
}
}
}
VS
class Welcome{
public static function functionName1{
//codes for functionName1 goes here
}
public static function functionName1{
//codes for functionName1 goes here
}
}
如果您只是在談論速度,這很容易測試:
class Testing
{
private static $x = 0;
public static function f1()
{
self::$x++;
}
public static function f2()
{
self::$x++;
}
public static function __callStatic($method, $params)
{
switch ($method) {
case 'f3':
self::$x++;
break;
case 'f4':
self::$x++;
break;
}
}
}
$start = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
Testing::f1();
Testing::f2();
}
$totalForStaticMethods = microtime(true) - $start;
$start = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
Testing::f3();
Testing::f4();
}
$totalForCallStatic = microtime(true) - $start;
printf(
"static method: %.3f\n__callStatic: %.3f\n",
$totalForStaticMethods,
$totalForCallStatic
);
我得到了static method: 0.187
和__callStatic: 0.812
,所以定義實際方法要快4倍以上。
我還要說,除非您有充分的理由,否則使用__callStatic
是不好的樣式。 這使得跟蹤代碼更加困難,並且IDE很難提供自動完成功能。 也就是說,在很多情況下都值得。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.