Home > Article > Backend Development > PHP development experience: quoting is a bad habit_PHP tutorial
When writing PHP programs, many people like to use a reference when passing parameters. Especially when an array is very large, I like to add.
function binsearch(&$arr, $key, $value)
{
$low = 0;
$high = count($arr);
while ($low <= $high) {
$mid = floor($low + ($high - $low) / 2);
$item = $arr[$mid][$ key];
if ($item == $value) {
return $mid;
} else if ($value > $item) {
$low = $mid + 1;
} else {
$high = $mid - 1;
}
}
return false;
}
Here, $mid is calculated by subtracting first and then adding, in order to prevent integer overflow. I didn’t mean to make it complicated.
I used the following code for testing:
$data = array();
for ($i = 0; $i < 1000000; $i++)
{
$data[] = array("sq" => $ i * 2);
}
var_dump(binsearch($data, "sq", 10000));
I found that when binsearching, it always takes about 0.2s. Theoretically speaking, 1 million data can be cycled 20 times at most. How could it be so slow?
Later I monitored the memory and found that the data array occupied 230M of memory. When binsearching, it occupied 60K of memory. However, in theory, binsearch
Shouldn't take up so much memory. Because, I think, I have used references and have not modified the data structure at all.
I was also puzzled. Later, I removed the reference parameter, and binsearch only took 0.0002s. It seemed that the reference consumed a lot of CPU resources.
PHP internally follows a copy on write principle. Actually this reference is redundant.
But why does it slow down when adding references? Today we will focus on this issue. After understanding the truth, everyone must know how to use quotations.
If you directly $a = &$data before calling binsearch, the speed of this reference will be very fast. It seems that the problem is definitely not caused by the reference itself.
This question actually involves how the zend engine manages PHP variables.