Search code examples
phpperformanceobjectmethodsstatic

Is static method faster than non-static?


EDIT::oh i forgot

class Test1{
    public static function test(){
        for($i=0; $i<=1000; $i++)
            $j += $i;       
    }   
}

class Test2{
    public function test() {
        for ($i=0; $i<=1000; $i++){
            $j += $i;
        }
    }

}

for this algorithm

$time_start = microtime();
$test1 = new Test2();
for($i=0; $i<=100;$i++)
    $test1->test();
$time_end = microtime();

$time1 = $time_end - $time_start;

$time_start = microtime();
for($i=0; $i<=100;$i++)
    Test1::test();
$time_end = microtime();    

$time2 = $time_end - $time_start;
$time = $time1 - $time2;
echo "Difference: $time";

i have results

Difference: 0.007561 

and these days, i am trying to make my methods static as possible. But is it really true, .. atleast for php


Solution

  • You should always use static when you don't need an object around you method, and use dynamic when you need an object. In the example you provides, you don't need an object, because the method doesn't interact with any properties or fields in your class.

    This one should be static, because it doesn't need an object:

    class Person {
        public static function GetPersonByID($id) {
            //run SQL query here
            $res = new Person();
            $res->name = $sql["name"];
            //fill in the object
            return $res;
        }
    }
    

    This one should be dynamic, because it uses the object it is in:

    class Person {
        public $Name;
        public $Age;
        public function HaveBirthday() {
            $Age++;
        }
    }
    

    The speed diffirence is minimal, but you have to create an object to run dynamic methods, and that object is saved in memory, so dynamic methods use more memory and a little more time.