I am having trouble understanding how to use static methods and properties well. I don’t understand the features and limitations of static methods and properties vs non-static methods and properties.
I understand that a static method can be called like this:
instead of this:
$myClass = new myClass();
But other than the static method call being 1 line shorter, what is the point? What mechanics are different? I am trying to understand this primarily for overhead purposes.
The particular classes I am working on are meant to be as fast as possible, as they are stats related and used everywhere in the app I am working on. I have heard php static methods are faster than non-static methods, so I decided to use them here. That is really the ONLY reason I am using static methods, as a few milliseconds can actually add up to non-trivial page load time increases due to the amount of stat collection done. (10x-50x multiplication or more per millisecond. And before you might ask, I cannot use a lower-level language, this isn’t a case of premature optimization, and I don’t care about testing for these classes.)
- Does it make sense to use a static method if the class has a constructor?
- Does it make sense to use a static method if that method calls another static method within it? (And what if the method is in a parent class, not the same class?)
- Does it make sense to use a static method if that method calls a non-static method within it? (And what if the method is in a parent class, not the same class?)
Pretend I have 3 classes. Class A is the parent class, and class B and C are children of class A and make use of A’s methods. Class B has a constructor, and in that constructor, constructs class A. Class C has no constructor of its own.
If I call a static method in class C, and this method does not call any other method, is class A loaded into memory (because it is the parent)? What if I call a static method in class C that in turn does call a static method in Class A?
My own benchmarking has yielded strange results that seem to show that static methods are slower, or equivalent to, non-static methods. This is sort of like the results here: http://stackoverflow.com/questions/1472721/performance-of-static-methods-vs-functions
But I am not confident that my benchmarks are testing the right things because I am not sure of the use-cases for static methods and how they are loaded behind the scenes. It’d be nice if I could make the case from first-principles that static methods should be slower or faster for my use-case.