php – 静态方法比非静态方法快吗?

前端之家收集整理的这篇文章主要介绍了php – 静态方法比非静态方法快吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
编辑::哦,我忘了
  1. class Test1{
  2. public static function test(){
  3. for($i=0; $i<=1000; $i++)
  4. $j += $i;
  5. }
  6. }
  7.  
  8. class Test2{
  9. public function test() {
  10. for ($i=0; $i<=1000; $i++){
  11. $j += $i;
  12. }
  13. }
  14.  
  15. }

对于这个算法

  1. $time_start = microtime();
  2. $test1 = new Test2();
  3. for($i=0; $i<=100;$i++)
  4. $test1->test();
  5. $time_end = microtime();
  6.  
  7. $time1 = $time_end - $time_start;
  8.  
  9. $time_start = microtime();
  10. for($i=0; $i<=100;$i++)
  11. Test1::test();
  12. $time_end = microtime();
  13.  
  14. $time2 = $time_end - $time_start;
  15. $time = $time1 - $time2;
  16. echo "Difference: $time";

我有结果

  1. Difference: 0.007561

而且这些天,我试图使我的方法尽可能的静态.但是真的是真的吗,至少为PHP

当你不需要你周围的对象的方法时,你应该总是使用静态的,并且当你需要一个对象时使用动态的.在您提供的示例中,您不需要对象,因为该方法不与您的类中的任何属性或字段进行交互.

这个应该是静态的,因为它不需要一个对象:

  1. class Person {
  2. public static function GetPersonByID($id) {
  3. //run sql query here
  4. $res = new Person();
  5. $res->name = $sql["name"];
  6. //fill in the object
  7. return $res;
  8. }
  9. }

这应该是动态的,因为它使用它所在的对象:

  1. class Person {
  2. public $Name;
  3. public $Age;
  4. public function HaveBirthday() {
  5. $Age++;
  6. }
  7. }

速度差异很小,但您必须创建一个对象来运行动态方法,并将该对象保存在内存中,因此动态方法使用更多的内存和更多的时间.

猜你在找的PHP相关文章