Is PHP file_get_contents memory and efficient data?

I create a push notification server that collects certain data from an external (third-party) html page, if I know that the information I need is in the first, for example. 5000 characters, will PHP use less memory if I specify MAX_LENGTH? Or is the whole page fully loaded into memory? Also, is the whole html page loaded or is the connection broken after the limit is reached? (and, in turn, saving data transfer costs)

$html = file_get_contents ("http://.....", false, null, -1, 5000); 

thanks.

+4
source share
3 answers

Yes, it saves memory and bandwidth ... I also checked the speed test (which doesnโ€™t quite correspond to this question, but is useful and assumes it stops reading the stream) and the memory test just to demonstrate, I didnโ€™t have a maximum memory test, but at least your $ html variable stores less information and stores 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 
+2
source

Digging through the source, starting here , following here, and finally ending with the _php_stream_copy_to_mem function, it looks like the file_get_contents() function will actually stop reading the stream as soon as it reaches the requested maximum length.

+2
source

Yes, because it uses the flow functions under the hood, it will actually stop when it reaches the limit. The documentation page also says

"file_get_contents () is the preferred way to read the contents of a file into a string. It will use memory matching methods, if supported by your OS, to improve performance.

so that he truly gives you the incentives you are looking for.

+2
source

Source: https://habr.com/ru/post/1389090/


All Articles