I'm relatively new to PHP and slowly learning the idiosyncrasies specific to the language. One thing I get dinged by a lot is that I (so I'm told) use too many function calls and am generally asked to do things to work around them. Here's two examples:
// Change this:
} catch (Exception $e) {
print "It seems that error " . $e->getCode() . " occured";
log("Error: " . $e->getCode());
}
// To this:
} catch (Exception $e) {
$code = $e->getCode();
print "It seems that error " . $code . " occured";
log("Error: " . $code);
}
2nd Example
// Change this:
$customer->setProducts($products);
// To this:
if (!empty($products)) {
$customer->setProducts($products);
}
In the first example I find that assigning $e->getCode()
to $code
ads a slight cognitive overhead; "What's '$code'? Ah, it's the code from the exception." Whereas the second example adds cyclomatic complexity. In both examples I find the optimization to come at the cost of readability and maintainability.
Is the performance increase worth it or is this micro optimization?
I should note that we're stuck with PHP 5.2 for right now.
I've done some very rough bench tests and find the function call performance hit to be on the order of 10% to 70% depending on the nature of my bench test. I'll concede that this is significant. But before that catch block is hit there was a call to a database and an HTTP end point. Before $products
was set on the $customer
there was a complex sort that happened to the $products
array. At the end of the day does this optimization justify the cost of making the code harder to read and maintain? Or, although these examples are simplifications, does anybody find the 2nd examples just as easy or easier to read than the first (am I being a wiener)?
Can anyone cite any good articles or studies about this?
Edit:
An example bench test:
<?php
class Foo {
private $list;
public function setList($list) {
$this->list = $list;
}
}
$foo1 = new Foo();
for($i = 0; $i < 1000000; $i++) {
$a = array();
if (!empty($a))
$foo1->setList($a);
}
?>
Run that file with the time
command. On one particular machine it takes an average of 0.60 seconds after several runs. Commenting out the if (!empty($a))
causes it to take an average of 3.00 seconds to run.
Clarification: These are examples. The 1st example demonstrates horrible exception handling and a possible DRY violation at the expense of a simple, non-domain-specific example.
$e->getCode();
is pretty trivial, and smacks of micro-optimisation; but a function that makes a db call to return 1000 rows would be significant if called repeatedly several times in succession. Profiling your code should give you timing figures for function calls – Pomiferous