6

I read some articles about PHP references and how they hurt performance. I also saw some tests, proving the same.

Most of those resources, claim that reason for that is because references disable copy-on-write.

But I don't understand why would that cause a problem? PHP is not going to copy array e.g, just because you passed it by reference.

function foo(&$var) {
    $var->test = 'bar';
    xdebug_debug_zval('var');
}

$data = new stdclass;
foo($data);

and result I receive

(refcount=3, is_ref=1),
object(stdClass)[1]
public 'test' => (refcount=1, is_ref=0),string 'bar' (length=3)

This shows that no copy was made, and that function is still using same variable (dealing with actual variable and not copy).

What have I missed, why is there a performance loss?

Ned
  • 3,961
  • 8
  • 31
  • 49
  • 3
    Can you include the code you used for your tests? Otherwise this question might be closed as too broad. – TylerH Mar 10 '16 at 17:34
  • thanks for the tip, I updated it with simple example. – Ned Mar 10 '16 at 17:46
  • Possible duplicate of [In PHP (>= 5.0), is passing by reference faster?](http://stackoverflow.com/q/178328/1255289) – miken32 Mar 17 '17 at 23:33

1 Answers1

-1

I tried using 3v4l.com website to have a benchmarck. You can find the sources here: https://3v4l.org/NqHlZ

Here are the results I got for current last PHP versions, for 10k iterations:

Output for 5.5.33

Avergages:
    - Object through reference, explicitly: 2.5538682937622E-6
    - Object through reference, implicitly: 1.8869638442993E-6
    - Array through copy-on-write: 1.9102573394775E-6
    - Array through reference: 9.3061923980713E-7

Output for 5.6.19

Avergages:
    - Object through reference, explicitly: 2.2409210205078E-6
    - Object through reference, implicitly: 1.7436265945435E-6
    - Array through copy-on-write: 1.1391639709473E-6
    - Array through reference: 8.7485313415527E-7

Output for 7.0.4

Avergages:
    - Object through reference, explicitly: 4.6207904815674E-7
    - Object through reference, implicitly: 3.687858581543E-7
    - Array through copy-on-write: 4.0757656097412E-7
    - Array through reference: 3.0455589294434E-7

So, for all last PHP versions, there's no performance issue on passing through reference instead of make a copy-on-write. The part "Object through reference, explicitly" is, in fact, not a way to code because all objects are passed through reference, no matter the "&" symbol used or not. Maybe using this symbol to explicitly pass the variable through reference when variable is an object is causing to reach a memory address containing another memory address containing the data, that would explain why it takes a little bit longer.

Community
  • 1
  • 1
niconoe
  • 1,191
  • 1
  • 11
  • 25