/    Sign up×
Community /Pin to ProfileBookmark

PHP Function Memory Considerations

I’m processing large files via PHP and I have some concerns regarding optimization of memory usage in the script.

For example, if I trim() a 300 MB file does PHP know to stream it internally, or does it actually load the whole thing into memory to process it?

Is any optimization achieved by doing:
$data = file_get_contents(<300 MB file>);
$trimmed = trim($data);

Versus:
$trimmed = trim(file_get_contents(<300 MB file>));

I have similar concerns for mdecrypt_generic() and other functions that could potentially process large amount of data, but don’t seem to have an explicit way to stream.

Please enlighten me, and thanks in advance.

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@NogDogMay 04.2010 — I would say it's about 99% likely that even if you do trim(file_get_contents($file)) that the entire file contents is in memory as a PHP string, at least until after the trim() completes and returns its value. So for at least a moment the entire file size would be in memory. If this is an issue, you may be better of using fopen() - fgets() - fclose(), dealing with the file line by line instead of one big chunk, if that is logically possible with what you need to do and assuming it's a text file which has line breaks.
×

Success!

Help @auxone spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...