dqlhsm9820 2011-01-24 08:25
浏览 179
已采纳

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

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

  • 写回答

5条回答 默认 最新

  • douchigu1723 2011-01-24 08:36
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配