Skip to content

Magic with memory usage of array #8896

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
woodholly opened this issue Jun 30, 2022 · 3 comments
Closed

Magic with memory usage of array #8896

woodholly opened this issue Jun 30, 2022 · 3 comments

Comments

@woodholly
Copy link

Description

The following code:

<?php
$a = array();
for($i=1; $i<=1000000;$i++) {
	$a[$i] = var_export(array("foobar$i"), true);
}
echo "done, memory usage = " . (memory_get_usage(true)/1024/1024) . "Mb\n";

Resulted in this output:

done, memory usage = 278.00390625Mb

But this code with var_export casted to "real" string:

<?php
$a = array();
for($i=1; $i<=1000000;$i++) {
	$a[$i] = "" . var_export(array("foob(ar$i"), true);
}
echo "done, memory usage = " . (memory_get_usage(true)/1024/1024) . "Mb\n";

Resulted in this output:

done, memory usage = 94.00390625Mb
  1. Why original var_export eats x3 more memory in comparison with string-casted variant ? (same thing with json_encode)
  2. Why casting using (string) does not help ?

What kind of magic is working here ?

PHP Version

PHP 7.4

Operating System

Ubuntu

@woodholly woodholly changed the title Magic with memory usage or array Magic with memory usage of array Jun 30, 2022
@alecpl
Copy link

alecpl commented Jun 30, 2022

Interesting. I confirm this on 3v4l.org in all supported versions. Number of iterations need to be at least 10000 to notice the memory usage difference (1000000 is too big there).

@arnaud-lb
Copy link
Member

arnaud-lb commented Jun 30, 2022

var_export uses a string builder internally that allocates a buffer a bit larger than necessary while building the string. The issue here is that the string is not copied to a smaller buffer at the end.

The cast to string does nothing when the value is already a string. The concatenation however will force the string to be reallocated, and will use the minimum amount of memory.

@arnaud-lb
Copy link
Member

Fixed in #8902. Thank you @woodholly !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants