php – 静态方法比非静态方法快吗?
发布时间:2020-12-13 17:34:30 所属栏目:PHP教程 来源:网络整理
导读:编辑::哦,我忘了 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; } }} 对于这个算法 $time_start = microtime();$test1 = new Test2();f
编辑::哦,我忘了
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; } } } 对于这个算法 $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"; 我有结果 Difference: 0.007561 而且这些天,我试图使我的方法尽可能的静态.但是真的是真的吗,至少为php
当你不需要你周围的对象的方法时,你应该总是使用静态的,并且当你需要一个对象时使用动态的.在您提供的示例中,您不需要对象,因为该方法不与您的类中的任何属性或字段进行交互.
这个应该是静态的,因为它不需要一个对象: class Person { public static function GetPersonByID($id) { //run SQL query here $res = new Person(); $res->name = $sql["name"]; //fill in the object return $res; } } 这应该是动态的,因为它使用它所在的对象: class Person { public $Name; public $Age; public function HaveBirthday() { $Age++; } } 速度差异很小,但您必须创建一个对象来运行动态方法,并将该对象保存在内存中,因此动态方法使用更多的内存和更多的时间. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |