Reputation: 2603
I'm making a push notification server that gathers specific data from an external (third-party) html page, if I know the information I need is within the first e.g. 5000 characters, will PHP actually use less memory if I state a MAX_LENGTH? Or is the whole page loaded entirely into memory anyway? Additionally, is the entire html page downloaded or is the connection broken once the limit is hit? (and in turn saving data transfer costs)
$html = file_get_contents ("http://.....", false, null, -1, 5000);
thanks.
Upvotes: 4
Views: 1747
Reputation: 14489
Yes, it does save memory and bandwidth... I also ran a speed test (which is not completely germane to this question, but is useful and suggests that it does stop reading the stream) and a memory test just to demonstrate. I did not run a peak memory test, but at the very least your $html variable will store less information and save memory there.
Time to get ALL characters of remote page 10 times: 6.0368211269379
Time to get ALL characters of remote page 10 times: 6.0158920288086
Time to get ALL characters of remote page 10 times: 5.8945140838623
Time to get ALL characters of remote page 10 times: 8.867082118988
Time to get ALL characters of remote page 10 times: 5.7686760425568
Time to get first ten characters of page 10 times: 4.2118229866028
Time to get first ten characters of page 10 times: 4.5816869735718
Time to get first ten characters of page 10 times: 4.2146580219269
Time to get first ten characters of page 10 times: 4.1949119567871
Time to get first ten characters of page 10 times: 4.1788749694824
Memory Useage First 10 characters:40048
Memory Useage ALL characters:101064
Upvotes: 4
Reputation: 5264
Yes because it uses stream functions under the hood, it will actually stop when it reaches the limit. Also on the documentation page it says
"file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance."
so it should actually give you the boosts you look for.
Upvotes: 2
Reputation: 9870
Digging through the source starting here, following to here, and finally ending up at the _php_stream_copy_to_mem function, it looks like the file_get_contents()
function will actually stop reading the stream once it reaches the requested max length.
Upvotes: 2