I just let my brain run wild and the results are again chaotic. It is kind of bothering me how in the very basics, programming itself can be pretty redundant.
Let's look at this snippet of code and analyze what it does
public function __construct($data = array(), $strict = false, $prefix = null) {
if (!$data) {
return;
}
foreach ($data as $key => $val) {
if ($prefix) {
if (($pos = strpos($key, $prefix)) === 0) {
$key = substr($key, 0, $pos);
} else {
continue;
}
}
if ($strict === false || property_exists($this, $key)) {
$this->$key = $val;
}
}
}
When constructing this object we can provide an array to fill in it's properties, however there is some filtering we can do. If we enable the strict parameter it will only fill in keys it already has, and if we supply a prefix parameter it will only fill in properties that correspond to keys starting with a certain prefix.
See, however, that we have n*2 if-statements evaluated in the given loop at the very least. Meaning if we have 100 elements in the $data
array there will be at least 200 if-statements evaluated. Wouldn't it be better if we could reduce that?
public function __construct($data = array(), $strict = false, $prefix = null) {
if (!$data) {
return;
}
if ($strict === false) {
if ($prefix) {
foreach ($data as $key => $val) {
if (($pos = strpos($key, $prefix)) === 0) {
$this->{substr($key, 0, $pos)} = $val;
}
}
} else {
foreach ($data as $key => $val) {
$this->$key = $val;
}
}
} else {
if ($prefix) {
foreach ($data as $key => $val) {
if (property_exists($this, $key) && ($pos = strpos($key, $prefix)) === 0) {
$this->{substr($key, 0, $pos)} = $val;
}
}
} else {
foreach ($data as $key => $val) {
if (property_exists($this, $key)) {
$this->$key = $val;
}
}
}
}
}
As we can clearly see, readability has gone to hell but nevertheless we have reduced the amount of expressions evaluated from 200 to 2 in the best case scenario when $strict === false
and prefix === null
- that is a 99% increase in efficiency, theoretically.
Mostly everything I said so far is theoretical, so the question is - Is there any actual benefit to example 2 opposed to example 1 regarding program execution?
Given that I have not graduated in computer science I'm not as familiar on programming (and php) internals and how code is evaluated and executed on a deeper level, but I have read this and that on how processors can shortcut redundant if-statements but as I said, am not as familiar to answer the question myself.