static call vs. dynamic call : Which one has better performance?
For example this is my class:
<?php
Class Example
{
public f开发者_如何学Gounction example_function()
{
echo "example code";
}
}
?>
Which one of the following will be best, performance-wise?
1)
Example::example_function();
2)
$example = new Example();
$example->example_function();
What is the difference between them?
It not a matter of performance. It really isn't. The difference, if there is one, is so minuscule as to be hardly measurable.
If you need to design your class with static methods, use static methods.
If you need to instantiate your class, you have no choice but to use object methods.
It's a class design decision that has nothing to do with performance.
The difference between the two as far as execution speed is probably insignificant. But they do two very different things.
Example::example_function();
is treating the class as a global singleton object. Theres only one Example object, and it might have some public methods that can be called anywhere the class has been included.
$example = new Example();
$example->example_function();
is creating an instance of the Example class, meaning there can be many Examples running around with different properties.
How you would use these two would depend entirely on the nature of your project and what you are trying to achieve.
If you're planning on accessing class elements, then you need to access the function through an instance of the class. For example, this is not legal when accessed through a static method call (Example::example()
):
class Example
{
private $str = 'example';
public function example()
{
echo $this->str;
}
}
So, the question isn't about performance, but about how you're going to use your class and/or functions.
You should really give the PHP OOP docs a read.
As some other comments suggest, It seems the question about performance is secondary. There are other decisions and strategies that will improve your performance, but that one seems more about purely design.
I would suggest it is a question of good design vs bad design strategy? And I explain myself.
If you don't need OO, then why are you using OO? I mean with that that it seems silly to create objects and then access them as if the would be standard procedural functions.
I was just investigating about that subject, so please feel free to debate against my opinion, I am very happy to receive feedback (positive or negative) about this :-).
精彩评论