问题
Im curious about getting an answer for a OOP question but can't find any info so far.
Here goes, writing classes and methods is it faster to pass in parameters for each method or use instance/field variables and $this->x;
Which would be faster at run time?
class ExampleByParameter(){
function SomeMethod($a,$b){
echo $a." ".$b;
return;
}
}
or
class ExampleByInstance(){
function __construct($a,$b){
$this->a=$a;
$this->b=$b;
}
function SomeMehtod(){
$a=$this->a;
$b=$this->b;
echo $a." ".$b;
return;
}
}
I would imagine their would be no difference with the examples above but im thinking there might be a significant difference with more complicated code.
回答1:
The performance differece is going to be negligible. You should really be deciding which pattern is best for your class structure.
Does your class depend on $a
and $b
to operate properly? Put them in the constructor.
Is SomeMethod
public? Does it do anything with the supplied variables beyond what it returns? If so, keep them as parameters.
In a large-scale project, you will gain more benefit from accurate class design vs negligible performance improvements.
来源:https://stackoverflow.com/questions/13007658/php-oop-performance-parameter-or-instance-variable