开发者

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

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 not looking for a discussion about the difference between the two or a discussion of which is "better." I'm only 开发者_运维技巧interested in relative performance between the two. Thanks in advance.

-Mike


Check this chart :)

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

grabbed from this article


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.


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜