When the function calls and passes in a large string, I usually pass by reference. Its intention prevents PHP from undergoing a copy of the string, thus reducing memory usage. However, I have seen the contrast in certain circumstances.
In the example below, the usage of mat memory is doubly, when passing the string by reference in the function, on the is_string () call.
Code:
$ buf = ''; Report_memory (___LINE__); $ Buf = file_get_contents ('./20MB.pdf'); Report_memory (___LINE__); Example ($ buf); Report_memory (___LINE__); Example of function (& amp; $ str) {report_memory (___ LINE__); Is_string ($ str); Report_memory (___LINE__); } Function report_memory ($ line = 0) {echo 'line:'. Str_pad ($ line, 3) "'; Echo 'Mem:' Str_pad (intval (memory_get_usage () / 1024) 'K', 8). ''; Echo 'peak:' str_pad (intval (memory_get_peak_usage () / 1024). 'K', 8). ''; Echo "\ n"; }
Output:
line: 2m: 625k peak: 631kg line: 5m: 21058 peak: 21076 line: 11m : 21058K line: 138m: Peak of 21058: 41494K Line: 8m: 21058 peak: 41494K
Function to replace context () Change ():
Example of function ($ str) {report_memory (__ LINE__); Is_string ($ str); Report_memory (___LINE__); }
Output:
line: 2m: 625k peak: 631kg line: 5m: 21058 peak: 21076 line: 11m : 21058 that crop: 21076 line: 13mm: 21058 peak: 21076 km Line: 8m: 21058 peak: 21076's
That's what I hope. Then why is the memory is doubling with is_string () when the variable is a reference?
Environment CentOS 6.6 is running a stock PHP 5.3.3.
The zend engine uses a lazy-copy mechanism unless the variable is modified, it Does not copy the variable. PHP creates a set of structures that is used to maintain the context, that is why in order to pass a variable in terms "really slow".
No comments:
Post a Comment