|
Posted by Chung Leong on 12/03/05 23:28
Chameleon wrote:
> THE QUESTION:
> If I want a FAST script, I must use & everywhere? (e.g. foreach ($b as &
> $v); )
You should only use references when necessary, i.e. when you want the
referenced variable to be modifed somewhere else down the line.
Improper use of references will slow down your code considerably. For
example, if you time the following loops, you'll find that the second
one is much slower:
//------------------first
$t = microtime(true);
for($z = 0; $z < 1000000; $z++) {
$b = $a;
$c = $b;
}
//------------------second
$t = microtime(true);
for($z = 0; $z < 1000000; $z++) {
$b = $a;
$c =& $b;
}
Why is the second loop slow? That's because the reference assignment to
$c forces a copy of the array to be made. The by-reference and by-value
mechanism in PHP is quite unlike that in C/C++. By-value in PHP means
share-read while by-reference means share-read-write. A variable cannot
do both at the same time. If $c and $b are sharing read-write access,
then $a and $b cannot be sharing just read access, as $a and $c are not
sharing read-write access. A good analogy is Jack lending Jill a
picture book. She is supposed to just read it. If she wants to give it
to her little brother to draw on, she had better get her your copy,
since that wasn't the agreement between her and Jack.
If you can ensure that given piece of data is always passed
by-reference, then you might gain some performance benefits. If
somewhere along the line though, it was passed by-value, then you take
a performance hit. That's one of the reason why in PHP 5 objects are
always passed by-reference. Because invoking a method implies passing
the object by reference ($this), objects should never be passed
by-value.
[Back to original message]
|