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

前端 未结 5 1462
天涯浪人
天涯浪人 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: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.

提交回复
热议问题