Skip to content

Instantly share code, notes, and snippets.

@aurelijusb
Last active December 30, 2015 23:08
Show Gist options
  • Save aurelijusb/7898365 to your computer and use it in GitHub Desktop.
Save aurelijusb/7898365 to your computer and use it in GitHub Desktop.
PHP array swap example.PHP saves memory when passing arrays by value and creating new ones in different order.Only symbols' table is updated.
<?php
$a = [1,2];
function f($b) {
xdebug_debug_zval('b');
return [$b[1], $b[0]];
}
xdebug_debug_zval('a');
$c = f($a);
xdebug_debug_zval('c');
// a: (refcount=1, is_ref=0)=array (0 => (refcount=1, is_ref=0)=1, 1 => (refcount=1, is_ref=0)=2)
// b: (refcount=3, is_ref=0)=array (0 => (refcount=1, is_ref=0)=1, 1 => (refcount=1, is_ref=0)=2)
// ^ as call by reference
// c: (refcount=1, is_ref=0)=array (0 => (refcount=2, is_ref=0)=2, 1 => (refcount=2, is_ref=0)=1)
// ^ swapped, but saving memory ^
<?php
class A { public $b; public $c; public $d; }
$a1 = new A();
$a1->b = "SOME BIG DATA";
xdebug_debug_zval('a1');
//a1: (refcount=1, is_ref=0)=class A { public $b = (refcount=1, is_ref=0)='SOME BIG DATA'; public $c = (refcount=1003, is_ref=0)=NULL; public $d = (refcount=2, is_ref=0)=NULL }
// ^ oobject link ^ First copy ^ every null pointer
$a2 = clone $a1;
xdebug_debug_zval('a1');
// a1: (refcount=1, is_ref=0)=class A { public $b = (refcount=2, is_ref=0)='SOME BIG DATA'; public $c = (refcount=1004, is_ref=0)=NULL; public $d = (refcount=3, is_ref=0)=NULL }
// ^ unique object link ^ Not copying big data
$a2->c = "Changed variable";
$a3 = clone $a2;
xdebug_debug_zval('a3');
// a3: (refcount=1, is_ref=0)=class A { public $b = (refcount=3, is_ref=0)='SOME BIG DATA'; public $c = (refcount=2, is_ref=0)='Changed variable'; public $d = (refcount=4, is_ref=0)=NULL }
// ^ a1, a2 and a3 shares this data ^ a2 and a3 shares
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment