views:

239

answers:

4

Hi all,

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  A: 

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.

Mark Baker
+4  A: 

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...

ircmaxell
+1 for the quote...
Fernando
Wrikken
-1: Didn't answer the question, pontificated instead. The question is related to use within WordPress; should plugins use static classes to encapsulate hooks or instances of classes so yes it can be thousands of times or more. There's no need for instances in this context so I've chosen static but some are staying static methods are too slow. I didn't know what the facts were so I came here to find the answer. Still don't know the answer...
MikeSchinkel
I did answer the question. I said don't worry about it. The difference will likely be very minor. Make the better architectural choice. It's a micro-optimization either way, so don't worry about it...
ircmaxell
+2  A: 

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.

Ryan Tenney
+3  A: 

check this chart :)

alt text

grabbed from this article

zolex
Anyone can produce fancy charts. Without information about the used test setup, it is meaningless. You could at least provide a link to where you got this from.
Gordon
I just added the link to the article
zolex