Skip to content

Magic with memory usage of array #8896

@woodholly

Description

@woodholly

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions