Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decrease memory usage when passing big variables around

For example:

a(wordwrap(str_repeat('abcdef', 500000), 160, "\n", true));    

function a($v){
  $v[1] = 'x';      
  $v = b($v);
  return $v;
}

function b($v){
  $v[2] = 'x';    
  $v = c($v);
  return $v;
}

function c($v){
  $v[3] = 'x';  
  d($v);    
}

function d($v){
  $v[4] = 'x';
  print $v;
}

This uses ~23 MB. I think because PHP is creating a copy of that text on each modification. If I just print the text once it uses 12 MB.

Can I somehow free the memory for the original variable before functions are called? Like

unset($v);
$v = c($v);

Obviously this won't work because $v is destroyed before it gets passed to c() lol. But I'd like to somehow let c() modify the same text. Like using references. (I tried references but they actually increase memory usage, probably because PHP makes more copies)

like image 563
Alex Avatar asked Aug 17 '26 20:08

Alex


1 Answers

Yes, you are right, PHP uses copy-on-write approach. You might wanna try references, e.g.:

function a(&$v){
    $v[1] = 'x';      
    $v = b($v);
    return $v;
}

I just noticed, that you tried references, are you sure that memory usage wasn't lower?

like image 189
Wintermute Avatar answered Aug 19 '26 10:08

Wintermute



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!