Performance of Singleton Class Instance Method vs.

2019-03-16 18: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 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

回答1:

Check this chart :)

grabbed from this article



回答2:

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.



回答3:

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.



回答4:

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.



回答5:

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.