19

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

Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
S L
  • 14,262
  • 17
  • 77
  • 116
  • 11
    The question you should ask yourself: Is the speed difference causing you any problems? If not, don't worry about it. – Sebastian Paaske Tørholm Jan 24 '11 at 08:27
  • 1
    don't know .. but if static methods are easy to call and i use it a lot. i had a preassumption that static method would be slow than regular one but my results show static are faster. just wanted to confirm (for knowledge let's say) – S L Jan 24 '11 at 08:29
  • 2
    Complete ditto. First make it work. It's pretty clear from your simple test that this is likely not a significant order of magnitude difference, so focus on the features and worry about millisecond-level optimizations if it becomes popular. However, by the time you get to that level you have probably re factored the entire thing a few times... – Hamy Jan 24 '11 at 08:29
  • Ah just saw your reply. If you're just looking for the knowledge then please ignore my comment ;) – Hamy Jan 24 '11 at 08:30
  • 100 iterations isn't really a considerable test... Try bumping that up to 100k or so, then see what kind of difference you get. If you have the patience, try getting up to 1M iterations. – Jeff Hubbard Jan 24 '11 at 08:31
  • it's okay!! i am the type of guy who wants to know what he's doing. thats all – S L Jan 24 '11 at 08:32
  • i tried million times and i still got the same (static faster than non static) – S L Jan 24 '11 at 08:33
  • 3
    Yes, static is faster. No, you do not want to use static. Try to mock a static class in a UnitTest. Then you know why. – Gordon Jan 24 '11 at 08:38
  • `static` methods can be used to group set of methods related some way, without polluting the global name space with simple collection of functions. – Amil Waduwawara Jan 24 '11 at 08:39
  • 1
    @Amil wrong, there is no difference between `Foo::test()` and `foo_test()`. All statics are effectively globals. Yes, Foo::test is just Foo in the global namespace, but whether you prefix a function with foo_ or put it into a class, is not a big difference. – Gordon Jan 24 '11 at 08:41
  • The only reason static methods are popular in PHP is because there was a complete lack of namespace support until the most recent version. You're just building function libraries with stupid access methods, which will be the first things to become obsolete once people adopt to the newest namespacing conventions. – Roger Halliburton Jan 24 '11 at 08:42
  • Since you asked for the performance aspect, I'll not mark this as duplicate, but related: http://stackoverflow.com/questions/1185605/when-to-use-static-vs-instantiated-classes – Gordon Jan 24 '11 at 08:48
  • I think it is a bit unfair to trivialize static methods just from unit-testing view of point. Which I'm sure 95% of developers don't even use at all. – samayo Nov 24 '13 at 20:08
  • [This post](http://stackoverflow.com/a/26592002/195835) on Stackoverflow gives some great benchmarks across different PHP versions and a good answer to the question. – Simon East May 01 '17 at 21:43

6 Answers6

39

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.

Jan Sverre
  • 4,617
  • 1
  • 22
  • 28
  • 6
    While this is the correct textbook answer, [static methods are death to testability](http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability) and should be avoided. – Gordon Jan 24 '11 at 08:39
19

Short Answer since I don't want to go on a rant to much:

It doesn't matter if it's faster. If you need something where performance is THAT important that you think about shaving of 0.02 nanoseconds per function call then you're not going to do it in PHP anyways.

Static methods make for untestable, unmaintainable, "global everything" code that is going to hurt you much more than anything else.

If you don't want to use proper OOP (and thats totally fine if you know what and why you are doing it) then please do so. Just don't do it because you want to save cpu time.

http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

http://sebastian-bergmann.de/archives/885-Stubbing-Hard-Coded-Dependencies.html

http://en.wikipedia.org/wiki/Class-based_programming

If you only click one link: http://www.scribd.com/doc/20893084/Advanced-OOP-and-Design-Patterns#scribd

Premature optimization is the root of all evil. Build code that is easy to maintain and if it's getting slow take a profile and it will most likely tell you that the filesystem oder the database is problem, one you got all that sorted out there will be some very specific pieces of php to optimize. If you got clean, changeable code you can speed those up.

ruleboy21
  • 5,510
  • 4
  • 17
  • 34
edorian
  • 38,542
  • 15
  • 125
  • 143
  • I think Stefan must have taken down his slideshare but it looks like someone else put a copy here, seems like a really good read... http://www.scribd.com/doc/20893084/Advanced-OOP-and-Design-Patterns – Carlton Apr 17 '14 at 10:08
  • 3
    "static methods make for untestable, unmaintainable, "global everything" code that is going to hurt you much more than anything else.". I disagree completely. Its even easiest to test a static method than a non static. Class:method() is easy than $obj=new Class(); $obj->method(). – magallanes Dec 18 '17 at 20:22
5

"Premature optimization is the root of all evil" was said 40 years ago by Donald Knuth. You know, back when you had the new 4004 microprocessor that Intel invented. That drum is beat as hard as any horse can be and I fail to see how it relates to the original question. In fact, I may have been lucky, but I haven't seen evidence of this rampant behavior in the field. Alas, someone on the internet has to be right before we can all tuck in for the night.

More on topic, I think the accepted answer is the most pragmatic and the first comment to the question is the right one to ask. Whether static vs. an instantiated code is faster is mostly dependent on the way the language is implemented and I don't see that any of these responses sufficiently answer the question in regards to PHP. Anyone know PHP and want to weigh in?

CappuccinoRob
  • 141
  • 2
  • 3
2

Generally, yes. Static methods and properties work faster (except in PHP 5.3).

You can refer to this more or less detailed comparison of static and non-static methods in PHP.

Stanislav
  • 903
  • 2
  • 9
  • 14
1

Similar question here: Does using static methods and properties in PHP use less memory?

I just improved the benchmark of Stanislav's link to have it live:

https://3v4l.org/rDpVv

Results for PHP 7.4.1:

Runs by case: 500000 
Memory usage at start: 426,320

Run                                 Duration    %       Memory
Dynamic                             0.0594      30%     496
Dynamic instantiated                0.0917      46%     0           #
Dynamic instantiated stored         0.1994      100%    48,967,472  # slowest
Storage only                        0.0422      21%     16,781,392
Cost of instations only when stored 0.1572      79%     32,186,O8O  # cost of stored instatiations minus storage cost (diff of 2 previous lines)
Static                              0.0870      44%     0           # equivalent to dynamic with instantiation
Singletons with many getInstance    0.1213      61%     376
Singletons with one getInstance     0.0669      34%     320         # equivalent to "Dynamic"
Functions assigning $GLOBALS        0.0605      30%     0           # more than 2 times longer than using "global"
Functions assigning a global        0.0458      23%     32          # fastest. 32bits allocated? probably passed by copy... odd
Functions with $counter by ref      0.0707      35%     0           # slow for functions
Functions with $counter static prop 0.0524      26%     0

Remarks:

  • "Functions modifying a global" is the fastest with 23%
  • "Instantiate, store then calling a dynamic method" is the longest so 100%
  • Storing instances cost a lot of memory and 21% of the total time
  • "Passing $counter as parameter by ref" is almost 2 times longer than "Functions modifying a global"
  • Calling a function modifying a static property is super fast, almost a half of calling a static method. Funny
  • MyClass::call() costs 75% of the time of Singleton::getInstance()->call() but 133% of $mySingleton->call()
  • MyClass::call() costs as much as (new MyClass)->call()
  • "Static" is equivalent in cost to "dynamic instatiated non stored". Really interesting!

Conclusions on dev practices (valid in jan 2020) :

  • Never use $GLOBALS, 'global $myVar' is super fast (and allocates 32 bits?)
  • Programming with global variables and functions only is the fastest PHP possible? Old school rocks!
  • Storing an instance for a lot of method calls then drop it is optimal.
  • Avoid to store a lot of instances.
  • "Instantiating for calling" and "Static calls" have the same cost

Cheers

PS: I cannot do more runs due to limitations even if the results are not 100% stable (I'm seen 20% variations on some refresh of the full bench) PS 2: if you want to disable the cache of 3v4l.org just add a space in the code wherever you want

Jean Claveau
  • 1,101
  • 1
  • 13
  • 15
0

If you intend to make your methods static and add a parameter to pass your class objects in, that is actually slower. I benchmarked a test with this and it's a considerable loss. Passing around objects through various static methods is a performance loss. It's better to keep them dynamic, in the object.

I am fairly certain that the performance is faster with dynamic methods because the calls are made in the same object. With using static methods in objects, there is an extra hop per call, as the call is not made within the object, but in the class.

It does reduce memory usage to use static methods. If you can house your methods in the class, the objects will be lighter-weight without them. But most importantly in my tests is accessibility. Direct access to methods is fastest, while access to static class methods is an extra hop. It's really a matter of processing versus memory. Nine times out of ten, dynamic is faster.

axiom82
  • 636
  • 1
  • 7
  • 15