Performance of Singleton Class Instance Method vs. Static Class Method in PHP?

前端 未结 5 1463
天涯浪人
天涯浪人 2021-02-06 12:06

I\'m interested in objective analysis of which is more performant; calling instance methods of a singleton class or methods of a static class. I\'ve already seen this so I\'m no

相关标签:
5条回答
  • 2021-02-06 12:34

    Unless you're calling them in a tight loop (meaning no other significant code, where the overhead of the call is significant) thousands or hundreds of thousands of times, don't worry about it. The difference is likely going to be under a microsecond, so it's not worth fretting over. Simply make the best architectural choice...

    Premature optimization is the root of all evil...

    Edit: To all the downvoters, here's a blog post that I wrote that describes why performance comparisons like this are all but useless.

    0 讨论(0)
  • 2021-02-06 12:45

    I'm a bit late to this conversation, but having just found the question I figured I would toss my thoughts into the ring for my first post to SO.

    As a quick experiment (after reading the article linked by zolex) I added a third test case to the article's benchmarks:

    $inst = TestSingleton::getInstance();  
    for($i=0;$i<$runs;$i++) $inst->test();
    

    The results weren't 100% consistent of course, but I found that most times when running 500,000 calls through all three methods, the above method was running anywhere from 2-3 seconds faster than either of the other two.

    Though I always cringe when I see the 'premature optimization' quote given, in this case I think it hits the nail on the head. The performance difference is minimal at best, and is usually in favor of the more sane singleton usage.

    0 讨论(0)
  • 2021-02-06 12:50

    In previous tests that I've done, I've found that calling static methods is faster than calling instance methods, and fractionally more memory efficient.... but the singleton shouldn't be dismissed purely for those reasons.

    0 讨论(0)
  • 2021-02-06 12:54

    Check this chart :)

    alt text

    grabbed from this article

    0 讨论(0)
  • 2021-02-06 12:54

    Before you can call the instance method of a singleton pattern object, you need to get the instance first, which requires a static method call:

    SomeClass::getInstance()->myMethod();
    // versus
    SomeClass::myMethod();
    

    So the first time you need access to that object in a function, you need to make a static method call first. Because function calls are never free, you are probably better off making the method static.

    0 讨论(0)
提交回复
热议问题