Reputation: 17004
My Question is about performance vs design. I have readed much about Getter and Setter in PHP. And the idea behind, is very good and usefull (Debugging, Sanitize).
So I started to do a Benchmark:
class Foo {
public $bar;
public function __construct($bar) {
$this->bar = $bar;
}
public function getBar() {
return $this->bar;
}
public function setBar($bar) {
$this->bar = $bar;
}
}
$foo = new Foo(42);
Debug::ProcessingTimeSinceLastCall();
//Without Setter and Getter
for ($i = 0; $i < 1000000; $i++) {
if ($foo->bar === 42) {
$foo->bar = 43;
} else {
$foo->bar = 42;
}
}
Debug::ProcessingTimeSinceLastCall('No Setter and Getter');
//With Getter and Setter
for ($i = 0; $i < 1000000; $i++) {
if ($foo->getBar() === 42) {
$foo->setBar(43);
} else {
$foo->setBar(42);
}
}
Debug::ProcessingTimeSinceLastCall('With Setter and Getter');
Result:
0.0000 Seconds (First call)
0.1428 Seconds (No Setter and Getter)
0.4366 Seconds (With Setter and Getter)
Setter and Getter takes 3 times more time. Is my Benchmark wrong?
I am in development of an big application, with thousands of those calls. Is it still a good practise to have getter and setter, if performance matters?
Upvotes: 2
Views: 1643
Reputation: 93666
Thousands of calls may not be relevant in the face of fetching data from a database and sending the response back out over the wire.
You talk about "thousands of calls". Your code can make one million calls to the setters/getters and only be slowed down 0.29 seconds. Do you have code that makes millions of calls, and that has a runtime such that you can notice a difference of 0.29 seconds?
Before you go optimizing, find out where the slow spots in your code are using a code profiler like XDebug: http://xdebug.org
Upvotes: 7