A Brief Analysis of the Reasons for the Higher Efficiency of PHP's Static Member Function

  • 2021-06-29 10:39:09
  • OfStack

As many php developers know, using static member functions of classes is more efficient than normal member functions of classes. This paper analyzes this issue from the application level.

Here is an example:

<?php // php Static Method Test 
header('Content-Type: text/html; charset=utf-8');
class xclass{
     public static $var1 = '1111111111111111';
     public $var2 = 'aaaaaaaaaaaaa';
     public function __construct()
    {
         $this -> var2 = 'bbbbbbbbbbbbbbbb';
         }
     public static function secho1()
    {
         echo self :: $var1 . '<hr />';
         }
     public function secho2()
    {
         echo $this -> var2 . '<hr />';
         }
     public function secho3()
    {
         echo 'cccccccccccccc<hr />';
         }
     }
 xclass :: secho1();
 xclass :: secho3();
 echo "------------------------------<br />";
 $xc = new xclass();
 $xc -> secho1();
 $xc -> secho2();
 ?>

Looking carefully at the example above, it is interesting to see that when secho1 () is defined as a static method, it can still be referenced as a dynamic method in the object instance of a dynamic class, while secho3 () can also be used as a static member function. From this level, it is not difficult to understand why a static member function is faster than a dynamic one.

For compatibility reasons, php's class members do not have a distinct dynamic or static component. All members are stored in a specific memory area as static members without explicit declaration, so calling static member functions is as fast as calling normal function 1.

However, invoking a dynamic class is different. It uses this class structure as a sample to regenerate an object instance in memory, so there is one more process. This may not be much for simple classes, but it has a significant effect on efficiency for complex classes.

Some people are worried about whether using static methods will cause too much memory usage. In fact, from the analysis above, you know that if you do not declare static methods, the system will still treat members as static, so the memory usage is almost the same for a class that is completely static and a class that is completely dynamic but does not declare instance objects, so for more direct logic,It is recommended that you use static member methods directly. Of course, it is not impossible to use static classes completely for some complex or visualized logic, but that will lose the meaning of the class. If so, why OOP? Static methods are especially suitable for logical classes in MVC mode by purpose.


Related articles: